레이블이 webapp인 게시물을 표시합니다. 모든 게시물 표시
레이블이 webapp인 게시물을 표시합니다. 모든 게시물 표시

2015년 4월 21일 화요일

Firefox App 개념 대충 정리

MDN App Center
https://developer.mozilla.org/en-US/Apps

[Quickstart]
https://developer.mozilla.org/en-US/Apps/Quickstart

[Getting Started, 한글판]
https://developer.mozilla.org/ko/Apps/Getting_Started

[App Manifest]
 : https://developer.mozilla.org/en-US/Apps/Build/Manifest

- manifest.webapp (.webapp extension은 필수)
- root directory 내에 위치
- JSON format, Content-Type은 application/x-web-app-manifest+json 이어야 함.
- manifest 에서 참조되는 internal path들은 same origin내에 존재해야 함.

- Firfox marketplace 등록 시 필수 항목들
 : name, description, launch_path( for Packaged Apps), icons(128x128 필수, 512x512 옵션), developer, default_locale, type
- generic Open Web Apps
 : name, description, icons(128x128 required, 512x512 recommended)

- optional fields
 . activities
  : 타 app에서 사용가능한 기능을 제공하는 Web Activities의 조합이며 어떤 activity를 지원하는지 정의. 하단은 png, gif 이미지를 share' 하는 activity를 지원하며

"activities": {
  "share": {
    "filters": {
      "type": [ "image/png", "image/gif" ]
    },
    "href": "foo.html",
    "disposition": "window",
    "returnValue": true
  }
}
 . installs_allowed_from
  : app이 설치 가능한 하나 이상의 URL, 구입해야 할 필요가 있는 app이라면 유용하게 사용될 수 있을 듯. default 값는 "*".

"installs_allowed_from": [
  "https://marketplace.firefox.com"
]
 . messages
  : 지정된 message들에 대해서 해당 page가 보여지도록 할 때 사용 됨.

 . permissions
  : app에서 사용할 device api들을 명시함.
  : 상세 permission list
   . https://developer.mozilla.org/en-US/Apps/Build/App_permissions
   . 3단계의 permission level이 존재함.
    > Web apps : basic level의 permission만을 사용 가능
    > Privileged apps : web app의 permission이상을 가짐. Hosted app 포함 안됨.
    > Internal (certified) apps : web app과 privileged app의 permission을 모두 가짐.
      : system level app들이나 Mozilla/operators/OEM들에서 만들어짐 앱들.


[Same Origin Policy]
https://developer.mozilla.org/en-US/Apps/Build/Building_apps_for_Firefox_OS/App_manifest_FAQ
http://charlie0301.blogspot.kr/2013/12/jquery-ajax-same-origin-policy-jsonp.html


[App installation]
 . app 설치 여부 확인할 경우 navigator.mozApps.getSelf() 를 사용
  : 특정앱의 설치 여부를 보려면 navigator.mozApps.checkInstalled()로 확인

var request = navigator.mozApps.getSelf();
request.onsuccess = function() {
  if (request.result) {
    // we're installed
  } else {
    // not installed
  }
};
request.onerror = function() {
  alert('Error checking installation status: ' + this.error.message);
};
 . app 설치를 위해서는 navigator.mozApps.install() 사용.

var request = navigator.mozApps.install("http://path.to/my/example.webapp");
request.onsuccess = function() {
  // great - display a message, or redirect to a launch page
};
request.onerror = function() {
  // whoops - this.error.name has details
};

[Device APIs]
https://developer.mozilla.org/en-US/Apps/Reference/Firefox_OS_device_APIs


[Simple Push]
 : https://developer.mozilla.org/en-US/docs/Web/API/Simple_Push_API
 : https://github.com/Redth/PushSharp/wiki/How-to-Configure-&-Send-FirefoxOS-Push-Notifications-using-PushSharp

Mozilla Push Notifications Flow
이미지  : https://camo.githubusercontent.com/2320ecab764e5493c5f3c1d28ef8e11430629de6/687474703a2f2f61726374757275732e6769746875622e696f2f6c6f6e646f6e5f6d65657475705f66697265666f786f732f696d672f706e735f6578616d706c652e706e67

 . Firefox OS에서만 지원.
 . App은 Simple Push를 사용하기 위해 unique한 endpoint를 Mozilla push 서버로 요청 함. 이후 전달받은 endpoint를 App은 자신의 server에 저장한 뒤 app을 wake 시키기 위해 사용함.
 . push시 endpoint와 version number도 함께 전달할 수 있어 이를 app에서 사용 가능함.
 . push를 unregister 하기 위해서는 PushManager.unregister()을 호출.
 . 사용하기 위해서는
  > manifest 파일 내 message로 "push", "push-register"로 event를 받을 page 등록.
  > manifest 파일 내 permissions에 "push" 등록.
  > PushManager.register()를 사용하여 endpoint 요청.
  > 수신 받은 endpoint를 추후 사용하기 위해 자신의 server에 등록하여 저장.

if (navigator.push) {
  // Request the endpoint. This uses PushManager.register().
  var req = navigator.push.register();
  
  req.onsuccess = function(e) {
    var endpoint = req.result;
      console.log("New endpoint: " + endpoint );
      // At this point, you'd use some call to send the endpoint to your server. 
      // For instance:
      /* 
      var post = XMLHTTPRequest();
      post.open("POST", "https://your.server.here/registerEndpoint");
      post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      post.send("endpoint=" + encodeURIComponents( endpoint ) );
      */
      // Obviously, you'll want to add .onload and .onerror handlers, add user id info,
      // and whatever else you might need to associate the endpoint with the user.
    }

   req.onerror = function(e) {
     console.error("Error getting a new endpoint: " + JSON.stringify(e));
   }
} else {
  // push is not available on the DOM, so do something else.
}
  > app에 push notification 수신 시 처리할 handler들을 등록 (window.navigator.mozSetMessageHandler())
    : push message handler는 index.html, main.js 아님 message handler만을 가지는 특정 파일(push-message.html)에 위치해야 한다. app이 종료되고 push message를 받는다면 message handler에서는 background로 처리를 해야할 지 app을 실행시켜야 할지 판단해야 하기 때문.
    : push-register message handler는 push server 변경, 일시 중지 등의 이유로 device의 internal identifier(UAID, User Agent Identifier)가 변경될 경우 이를 알려 app들이 다시금 endpoint를 register하도록 하기 위해 호출 된다.

  > notification 보내기

curl -X PUT -d "version=5" https://updates.push.services.mozilla.com/update/abcdef01234567890abcdefabcdef01234567890abcdef

[Contacts API]
 : https://developer.mozilla.org/en-US/docs/Web/API/Contacts_API
 . Firefox OS와 Firefox mobile(Android)에서 지원
 . system의 address book에 저장된 contact들을 접근하려면 navigator.mozContacts property를 사용해야 한다.
 . 연락처 추가, 검색, 수정, 삭제 지원
 . 연락처 찾기
  : ContactManager.find(), ContactManager.getAll()을 사용함.

[Notification API]
 : https://developer.mozilla.org/ko/docs/Web/API/notification

 . HTML5 feature라 Firefox외 Android browser, Chrome desktop 에서 지원한다.
  : http://caniuse.com/#feat=notifications
 . 구현 방법
  : https://developer.mozilla.org/en-US/docs/Web/API/Notification/Using_Web_Notifications

2015년 4월 16일 목요일

Chrome App 개념 대충 살펴보기

그냥 찾아봄.

[Create Your First App]
https://developer.chrome.com/apps/first_app

1. manifest 생성
 . chrome app에서는 background로 실행되는 script를 정할 수 있음.

2. background script 생성
 . background로 주기적으로 실행되며 event에 따라 app을 관리함.

3. window page 생성
 . 화면에 app을 보여주기 위해.
4. App icon 정하기
5. Chrome상에서 App launching
 . Chrome setting icon > Tools > Extension
   : Developer mode check 되어 있는지 확인
   : Load unpacked extension 버튼 클릭 후 app folder 선택

* 간단하네...


[Chrome App 관련 개념들]
: https://developer.chrome.com/apps/app_architecture

. Chrome App은 browser tab이 아닌 그냥 비어 있는 사각형에 표시되므로 특성에 따라 UI를 구성해야 함.
. Chrome App에서는 오프라인에서의 동작, 보안의 이유로 local상에서 main page를 위치하도록 하고 있음.

how app container model works

[App Life Cycle]

Life 설치 부터 삭제 까지의 주요 상황은 다음과 같음
- Instaillation : app 설치 시 permission을 사용자로부터 획득
- Startup : event page가 load되고 launch() event가 발생되면 app을 실행함.'
- Termination : app이 종료되면 종료 시 상태를 저장한다.
- Update : Chrome App은 언제나 업데이트 될 수 있지만 startup/termination 단계에서는 변경안됨.
- Uninstallation : 사용자가 app을 삭제하면 executing code와 private data는 모두 삭제 됨.

좀 더 자세히 풀어보면
: https://developer.chrome.com/apps/app_lifecycle

how app lifecycle works

아래와 같이 event Script에서 onLaunched 시 window를 표시함을 볼 수 있음.
chrome.app.runtime.onLaunched.addListener(function() {
  chrome.app.window.create('main.html', {
    id: 'MyWindowID',
    bounds: {
      width: 800,
      height: 600,
      left: 100,
      top: 100
    },
    minWidth: 800,
    minHeight: 600
  });
});
또한 설치, 중지, 재시작 되었을 때 chrome.runtime의 event listener로 처리할 수 있음.
=> https://developer.chrome.com/extensions/runtime#events


[Security Model]

Chrome App들은 CSP(Content Security Policy)를 따라야 한다고 하고 있음.

- Chrome App들은 사용하는 API들에 따른 permission을 명시적으로 알려야 함.
- Chrome App들은 분리된 storage, external content기반으로 분리된 process를 재사용함. 즉 다른 Chrome App들의 data, Chrome Browser의 Web page의 data를 접근할 수 없음. (cookie도 포함)

[Content Security Policy]
: https://developer.chrome.com/apps/contentSecurityPolicy
- 제약 사항들
 . inline scripting 사용 불허
 . video, audio를 제외한 external resources를 접근 불허
 . iframe 내 resource들을 embed 못함.
 . string-to-JavaScritp methods 사용 불가(eval(), new Function())

위 제약사항들에 대해서 대안으로 templating libraries, XMLHttpRequest를 사용한 external resoruce 접근, webview tag 사용을 말하고 있음.



[Chrome App Sample]
https://github.com/GoogleChrome/chrome-app-samples

[Hello World]
: https://github.com/GoogleChrome/chrome-app-samples/tree/master/samples/hello-world

예제의 진리.. hello world 
간단하다 화면에 Chrome icon과 hello world가 찍힌다.

manifest는 아래과 같고 background script는 main.js임.
{
"manifest_version": 2,
"name": "Hello World",
"version": "2.1",
"minimum_chrome_version": "23",
"icons": {
"16": "icon_16.png",
"128": "icon_128.png"
},
"app": {
"background": {
"scripts": ["main.js"]
}
}
}

background script에서는 
chrome app onLaunch event에서 화면에 index.html을 띄워주고 있음.

chrome.app.runtime.onLaunched.addListener(function() {
  // Center window on screen.
  var screenWidth = screen.availWidth;
  var screenHeight = screen.availHeight;
  var width = 500;
  var height = 300;

  chrome.app.window.create('index.html', {
    id: "helloWorldID",
    outerBounds: {
      width: width,
      height: height,
      left: Math.round((screenWidth-width)/2),
      top: Math.round((screenHeight-height)/2)
    }
  });
});
스크린샷은 직접 해서 보시라. :)

2015년 1월 18일 일요일

Debugging Android WebView, Chrome

[Chrome 개발자 도구를 사용한 원격 디버깅]
https://developer.chrome.com/devtools/docs/remote-debugging

chrome 개발자 툴을 사용하여 Android WebView를 원격에서 디버깅 가능함.

디버깅을 위해서 전제 조건은
- PC에 Chrome 32 이상 버전이 설치 되어야 함.
- Android 기기가 USB로 연결되어야 하고 인식도 되어야 함. (개발자 옵션의 디버깅 체크)
   (인식을 위해 Android Studio를 실행하는 것도 방법)
- Android Chrome 디버깅의 경우 Android 4.0 이상
- Android WebView를 디버깅 하기 위해서는 Android 4.4 이상

* 자세한 설정은 위 링크 참조

- WebView 디버깅을 위해서는 아래 코드를 앱에 포함해야 함.
WebView debugging must be enabled from within your application. To enable WebView debugging, call the static method setWebContentsDebuggingEnabled on the WebView class.
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
      WebView.setWebContentsDebuggingEnabled(true);
  }
This setting applies to all of the application's WebViews.
Tip: WebView debugging is not affected by the state of the debuggable flag in the application's manifest. If you want to enable WebView debugging only when debuggable istrue, test the flag at runtime.
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    if (0 != (getApplicationInfo().flags &= ApplicationInfo.FLAG_DEBUGGABLE))
    { WebView.setWebContentsDebuggingEnabled(true); }
  }


[WebView의 console.log 확인]

http://developer.android.com/guide/webapps/debugging.html

Android 2.1 이상에서는 WebChromeClient의 onConsoleMessage()를 구현해서 로그를 직접 출력 하라고 되어 있음. (아래는 API level 8 이상일 경우)


WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebChromeClient(new WebChromeClient() {
  public boolean onConsoleMessage(ConsoleMessage cm) {
    Log.d("MyApplication", cm.message() + " -- From line "
                         + cm.lineNumber() + " of "
                         + cm.sourceId() );
    return true;
  }
});

하지만 그냥 출력이 되는 경우도 있는 듯..

일단 내가 가진 galaxy s4에서는 Log Message에서 console 을 포함하거나
Log Tag가 chromium 이면 WebView에서 출력하는 console.log를 확인할 수 있음.

I/chromium﹕ [INFO:CONSOLE(78)] "Hello World!!!", source: http://192.168.0.1/wa/ (78)


[Debugging with Chrome DevTools]


Chrome DevTools Overview
: https://developer.chrome.com/devtools/index

* chrome://inspect 창에서 안드로이드 기기가 보이지 않는다면
Android Studio를 실행하고 아래 Android 로그창을 열어봐라.(ADB가 초기화 될것임)

* web 페이지의 cache를 삭제 하기 위해서 별도의 metatag를 사용할 필요 없이 dev tools 설정에서 General > "Disable cache (while DevTools is open)" 을 사용하되 dev tools가 실행되어 보여지는 상태여야 한다.

Remote Debugging
: https://developer.chrome.com/devtools/docs/remote-debugging


크롬 개발자 도구
: http://opentutorials.org/course/580


우리가 몰랐던 크롬 개발자 도구 by 박재성
: http://www.slideshare.net/netil/ss-28588952


[FireFox Developers Edition]
: https://www.mozilla.org/en-US/firefox/developer/

- FireFox 개발자 버전이며 개발자를 위한 다양한 툴이 제공됨
- CSS 수정이 용이(editing)하며 바로 화면에 적용되어 수정내역을 확인할 수 있다
  : 개발자 도구 > Style Editor 에서 수정 및 저장.
  : 하지만 렌더링 결과물이 Chrome, IE와 좀 차이가 나서 후 조정이 필요하다.