WebAPIs & Apps - Mozilla London


Published on

Published in: Technology

WebAPIs & Apps - Mozilla London

  1. FIREFOX OS WebAPIs & Apps
  2. @robertnyman
  3. Using HTML5, CSS andJavaScript together with anumber of APIs to build appsand customize the UI.
  4. https://addons.mozilla.org/firefox/addon/firefox-os- simulator/
  5. Droid@Screenhttp://blog.ribomation.com/droid-at-screen/
  6. Open Web Apps
  7. Web apps are apps built using standard Web technologies. They work in any modern Web browser.The Open Web apps project proposes some small additions to existing sites to turn them into apps. These apps run on desktop browsers and mobile devices.
  8. https://developer.mozilla.org/docs/Apps/ Getting_Started
  9. Steps to Take
  10. Develop Web App using1. HTML5, CSS, & Javascript2. Create an app manifest file3. Publish/install the app
  11. 1.Develop Web App usingHTML5, CSS & JavaScript
  12. Reuse any existing web site/app or develop from scratch with open web standards. Utilize HTML5 features such as localStorage, offline manifest, IndexedDB and access Web APIs for more options. Responsive web design for adapting to varying resolutions and screen orientation.
  13. 2.Create an app manifest file
  14. Create a file with a .webapp extension
  15. { "version": "1.0", "name": "MozillaBall", "description": "Exciting Open Web development action!", "icons": { "16": "/img/icon-16.png", "48": "/img/icon-48.png", "128": "/img/icon-128.png" }, "developer": { "name": "Mozilla Labs", "url": "http://mozillalabs.com" }, "installs_allowed_from": ["*"], "appcache_path": "/cache.manifest", "locales": { "es": { "description": "¡Acción abierta emocionante del desarrollo del Web!", "developer": { "url": "http://es.mozillalabs.com/" } }, "it": { "description": "Azione aperta emozionante di sviluppo difotoricettore!", "developer": { "url": "http://it.mozillalabs.com/" } } }, "default_locale": "en"}
  16. MANIFEST CHECKER http://appmanifest.org/
  17. Serve with Content-type/MIME type:application/x-web-app-manifest+json
  18. Apache - in mime.types:application/x-web-app-manifest+json webappApache - in .htaccess:AddType application/x-web-app-manifest+json webappNGinx - in mime.types:types { text/html html htm shtml; text/css css; text/xml xml; application/x-web-app-manifest+jsonwebapp;}
  19. IIS:In IIS Manager, right-click the localcomputer, and click Properties.Click the MIME Types button.Click New.In the Extension box, type the file nameextension.In the MIME type box, type a descriptionthat exactly matches the file type definedon the computer.Click OK.
  20. curl -I http://mozillalabs.com/manifest.webapp
  21. 3.Publish/install the app
  22. Firefox Marketplace
  23. https://marketplace.firefox.com/
  24. https://marketplace.firefox.com/developers/
  25. Installing/hosting the app
  26. var request = navigator.mozApps.install( "http://mozillalabs.com/MozillaBall.webapp", { user_id: "some_user" });request.onsuccess = function() { // Success! Notification, launch page etc}request.onerror = function() { // Failed. this.error.name has details}
  27. var request = navigator.mozApps.installPackage( "http://mozillalabs.com/manifest.webapp");request.onsuccess = function() { // Success!}request.onerror = function() { // Failed.}
  28. Packaged vs. Hosted Apps
  29. A packaged app is an Open Web App that has all of its resources(HTML, CSS, JavaScript, app manifest, and so on) contained in a zip file, instead of having its resources on a Web server.A packaged app is simply a zip file with the app manifest in its root directory. The manifest must be named manifest.webapp.
  30. Can be privileged apps with more API access than hosted appsSpecial protocol internal to the zip file: app://<uuid>Manifest file must be named manifest.webappResources are accessed from the zip file, which is stored on the device where theapp is installedInstalled with a different mozApps API function: installPackage()Enforce a specific Content Security Policy for all application contentCan embed remote content in iframes, but that content will not have access toprivileged APIs nor will it have the default CSP applied to itHave an update process for getting new versions of the app to users. Hostedapps do not need this process.
  31. https://developer.mozilla.org/docs/Apps/ For_Web_developers
  32. WebAPIs
  33. The Mozilla WebAPI team is pushing theenvelope of the web to include --- and in placesexceed --- the capabilities of competing stacks.
  34. https://wiki.mozilla.org/WebAPI
  35. Security Levels
  36. Granted by default Granted by authorized storeSafe web APIs that don’t expose privacy Privacy and security sensitive APIs suchsensitive data. WebGL, fullscreen, as Contacts APIaudio, etc. Verified by signatureGranted by user Highly privileged APIs such as radiolocation, camera, file system access access (dialer)Granted when installedNo quota for localStorage, IndexedDB,offline cache
  37. Web Content Certified Web AppRegular web content Device-critical applicationsInstalled Web AppA regular web appPrivileged Web AppMore access, more responsibility
  38. https://wiki.mozilla.org/WebAPI#Planned_for_initial_release_of_B2G_. 28aka_Basecamp.29
  39. "permissions": { "contacts": { "description": "Required for autocompletion in the share screen", "access": "readcreate" }, "alarms": { "description": "Required to schedule notifications" }}
  40. AlarmAPI FMRadioBrowserAPI geolocationContacts systemXHRdevice-storage:music/device-storage:videos/ TCP Socket APIdevice-storage:pictures/device-storage:sdcard: wake-lock-screen Add, read, or modify files stored at a central location on the device. access property required: one of readonly, readwrite, readcreate, or createonly. NEED PERMISSION
  41. Vibration API (W3C) Web ActivitiesScreen Orientation Push Notifications APIGeolocation API WebFM APIMouse Lock API (W3C) WebPaymentOpen WebApps IndexedDB (W3C)Network Information API (W3C) Ambient light sensorBattery Status API (W3C) Proximity sensorAlarm API Notification REGULAR APIS
  43. var battery = navigator.battery;if (battery) { var batteryLevel = Math.round(battery.level * 100) + "%", charging = (battery.charging)? "" : "not ", chargingTime = parseInt(battery.chargingTime / 60, 10, dischargingTime = parseInt(battery.dischargingTime / 60, 10); // Set events battery.addEventListener("levelchange", setStatus, false); battery.addEventListener("chargingchange", setStatus, false); battery.addEventListener("chargingtimechange", setStatus, false); battery.addEventListener("dischargingtimechange", setStatus, false);}
  45. var notification = navigator.mozNotification;notification.createNotification( "See this", "This is a notification", iconURL);
  47. // Portrait mode:screen.mozLockOrientation("portrait");/* Possible values: "landscape" "portrait" "landscape-primary" "landscape-secondary" "portrait-primary" "portrait-secondary"*/
  49. // Vibrate for one secondnavigator.vibrate(1000);// Vibration pattern [vibrationTime, pause,…]navigator.vibrate([200, 100, 200, 100]);// Vibrate for 5 secondsnavigator.vibrate(5000);// Turn off vibrationnavigator.vibrate(0);
  51. var pay = navigator.mozPay(paymentToken);pay.onsuccess = function (event) { // Weee! Money!};
  53. var connection = window.navigator.mozConnection, online = connection.bandwidth > 0, metered = connection.metered;
  55. var alarmId1, request = navigator.mozAlarms.add( new Date("May 15, 2012 16:20:00"), "honorTimezone", { mydata: "my event" } );request.onsuccess = function (event) { alarmId1 = event.target.result;};request.onerror = function (event) { console.log(event.target.error.name);};
  56. var request = navigator.mozAlarms.getAll();request.onsuccess = function (event) { console.log(JSON.stringify(event.target.result));};request.onerror = function (event) { console.log(event.target.error.name);};
  57. navigator.mozAlarms.remove(alarmId1);
  58. navigator.mozSetMessageHandler( "alarm", function (message) { // Note: message has to be set in the manifest file console.log("Alarm fired: " + JSON.stringify(message)); });
  59. { "messages": ["alarm"]}
  61. window.addEventListener("deviceproximity", function (event) { // Current device proximity, in centimeters console.log(event.value); // The maximum sensing distance the sensor is // able to report, in centimeters console.log(event.max); // The minimum sensing distance the sensor is // able to report, in centimeters console.log(event.min);});
  63. window.addEventListener("devicelight", function (event) { // The level of the ambient light in lux console.log(event.value);});
  64. window.addEventListener("lightlevel", function (event) { // Possible values: "normal", "bright", "dim" console.log(event.value);});
  65. window.addEventListener("devicelight", function (event) { // The lux values for "dim" typically begin below 50, // and the values for "bright" begin above 10000 console.log(event.value);});
  66. Device Storage APIBrowser APITCP Socket APIContacts APIsystemXHR PRIVILEGED APIS
  68. var deviceStorage = navigator.getDeviceStorage("videos");
  69. // "external", "shared", or "default".deviceStorage.type;// Add a file - returns DOMRequest with file namedeviceStorage.add(blob);// Same as .add, with provided namedeviceStorage.addNamed(blob, name);// Returns DOMRequest/non-editable File objectdeviceStorage.get(name);// Returns editable FileHandle objectdeviceStorage.getEditable(name);// Returns DOMRequest with success or failuredeviceStorage.delete(name);// Enumerates filesdeviceStorage.enumerate([directory]);// Enumerates files as FileHandlesdeviceStorage.enumerateEditable([directory]);
  70. var storage = navigator.getDeviceStorage("videos"), cursor = storage.enumerate();cursor.onerror = function() { console.error("Error in DeviceStorage.enumerate()", cursor.error.name);};cursor.onsuccess = function() { if (!cursor.result) return; var file = cursor.result; // If this isnt a video, skip it if (file.type.substring(0, 6) !== "video/") { cursor.continue(); return; } // If it isnt playable, skip it var testplayer = document.createElement("video"); if (!testplayer.canPlayType(file.type)) { cursor.continue(); return; }};
  72. var contact = new mozContact();contact.init({name: "Tom"});var request = navigator.mozContacts.save(contact);request.onsuccess = function() { console.log("Success");};request.onerror = function() { console.log("Error")};
  73. WebTelephony WebBluetoothWebSMS Permissions APIIdle API Network Stats APISettings API Camera APIPower Management API Time/Clock APIMobile Connection API Attention screenWiFi Information API Voicemail CERTIFIED APIS
  75. // Telephony objectvar tel = navigator.mozTelephony;// Check if the phone is muted (read/write property)console.log(tel.muted);// Check if the speaker is enabled (read/write property)console.log(tel.speakerEnabled);
  76. // Place a callvar cal = tel.dial(“123456789”);
  77. // Receiving a calltel.onincoming = function (event) { var incomingCall = event.call; // Get the number of the incoming call console.log(incomingCall.number); // Answer the call incomingCall.answer();};// Disconnect a callcall.hangUp();// Iterating over calls, and taking action depending on theirchanged statustel.oncallschanged = function (event) { tel.calls.forEach(function (call) { // Log the state of each call console.log(call.state); });};
  78. WEBSMS
  79. // SMS objectvar sms = navigator.mozSMS;// Send a messagesms.send("123456789", "Hello world!");
  80. // Recieve a messagesms.onreceived = function (event) { // Read message console.log(event.message);};
  82. { "activities": { "share": { "filters": { type: ["image/png", "image/gif"], } "href": "sharing.html", "disposition": "window" } }}
  83. var activity = new MozActivity({ name: "view", data: { type: "image/png", url: ... }});activity.onsuccess = function () { console.log("Showing the image!");};activity.onerror = function () { console.log("Cant view the image!");};
  84. var register = navigator.mozRegisterActivityHandler({ name: "view", disposition: "inline", filters: { type: "image/png" }});register.onerror = function () { console.log("Failed to register activity");}
  85. navigator.mozSetMessageHandler("activity", function (a) { var img = getImageObject(); img.src = a.source.url; // Call a.postResult() or a.postError() if // the activity should return a value});
  86. Future APIs
  87. Resource lock API Spellcheck APIUDP Datagram Socket API LogAPIPeer to Peer API Keyboard/IME APIWebNFC WebRTCWebUSB FileHandle APIHTTP-cache API Sync APICalendar API
  88. Web Apps from Mozilla
  89. Dialer Alarm ClockContacts CameraSettings NotesSMS First Run ExperienceWeb browser NotificationsGallery Home ScreenVideo Player Mozilla MarketplaceMusic Player System UpdaterE-mail (POP, IMAP) Localization SupportCalendar
  90. https://hacks.mozilla.org/2013/01/hacking-gaia-for- firefox-os-part-1/
  91. Installing apps
  92. FIREFOX OS BOILERPLATE APPhttps://github.com/robnyman/Firefox-OS-Boilerplate-App
  93. FXOSSTUBhttps://hacks.mozilla.org/2012/12/fxosstub-a-minimalists-working-example-of-the-design-guide-rules-for-firefox-os/
  94. MORTARhttps://hacks.mozilla.org/2013/01/writing-web-apps-quickly-with-mortar/
  95. Getting help
  96. irc://irc.mozilla.org/ #openwebapps
  97. https://lists.mozilla.org/listinfo/dev-webapps
  98. Trying things out
  99. Robert Nymanrobertnyman.comrobert@mozilla.comMozilla @robertnyman