Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Service Worker Sample for posting messages from a page that isn't controlled #94

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions service-worker/install-time-post-message/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Service Worker Sample: Posting Messages During Installation
===
See https://googlechrome.github.io/samples/service-worker/install-time-post-message/index.html for a live demo.

Learn more at http://www.chromestatus.com/feature/6561526227927040
181 changes: 181 additions & 0 deletions service-worker/install-time-post-message/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
<!doctype html>
<!--
Copyright 2015 Google Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta name="description" content="Sample of using postMessage to communicate with Service Workers during installation.">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>Service Worker Sample: Posting Messages During Installation</title>

<!-- Add to homescreen for Chrome on Android -->
<meta name="mobile-web-app-capable" content="yes">
<link rel="icon" sizes="192x192" href="../../images/touch/chrome-touch-icon-192x192.png">

<!-- Add to homescreen for Safari on iOS -->
<!-- TODO: Replace PLACEHOLDER with feature name. -->
<meta name="apple-mobile-web-app-title" content="PLACEHOLDER Sample">

<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<link rel="apple-touch-icon-precomposed" href="../../images/apple-touch-icon-precomposed.png">

<!-- Tile icon for Win8 (144x144 + tile color) -->
<meta name="msapplication-TileImage" content="images/touch/ms-touch-icon-144x144-precomposed.png">
<meta name="msapplication-TileColor" content="#3372DF">

<link rel="icon" href="../../images/favicon.ico">

<link rel="stylesheet" href="../../styles/main.css">

<script>
// Service workers require HTTPS (http://goo.gl/lq4gCo). If we're running on a real web server
// (as opposed to localhost on a custom port, which is whitelisted), then change the protocol to HTTPS.
if ((!location.port || location.port == "80") && location.protocol != 'https:') {
location.protocol = 'https:';
}
</script>

</head>

<body>
<h1>Service Worker Sample: Posting Messages During Installation</h1>

<p>Available in <a href="http://www.chromestatus.com/feature/6561526227927040">Chrome 40+</a></p>

<p>
This sample demonstrates using the <a href="https://html.spec.whatwg.org/multipage/workers.html#dom-worker-postmessage"><code>postMessage</code></a>
interface to communicate with a Service Worker that has just been installed, and is not yet controlling the page.
This allows for immediate communication with a Service Worker, immediately after it has been installed, without
waiting for the next time the user visits a page in the Service Worker's scope.
</p>

<p>
To communicate with a Service Worker that has just been installed, we can use the <code>ServiceWorkerRegistration</code>
object returned when the Service Worker was registered. This object contains an <code>installing</code> attribute
which represents the installing Service Worker.
</p>
<pre><code>
navigator.serviceWorker.register('./service-worker.js').then(function(registration) {
if (registration.installing) {
// If ServiceWorkerRegistration.installing is set, then this page isn't actively controlled
// by a Service Worker, but one was just installed.
registration.installing.postMessage({'message': 'Hello installing Service Worker'});
} else if (navigator.serviceWorker.controller) {
// If .controller is set, then this page is being actively controlled by the Service Worker.
navigator.serviceWorker.controller.postMessage({'message': 'Hello active Service Worker'});
}
});
</code></pre>

<p>
Visit <code>chrome://inspect/#service-workers</code> and click on the "inspect" link below
the registered Service Worker to view logging statements for the various actions the
<code><a href="service-worker.js">service-worker.js</a></code> script is performing.
</p>

<div class="output">
<div id="status"></div>

<div id="commands" style="display: none">
<div>
<label for="message">Message text:</label>
<input id="message" type="text" size="50" value="Top secret message">
<button id="send-message-registration">Send Message using ServiceWorkerRegistration.installing</button>
<button id="send-message-controller">Send Message using navigator.serviceWorker.controller</button>
</div>
</div>
</div>

<script>
// This will be used to store ServiceWorkerRegistration.installing for easy access
var serviceworkerRegistrationInstalling;

function setStatus(statusMessage) {
document.querySelector('#status').textContent = statusMessage;
}

function showCommands() {
document.querySelector('#send-message-registration').addEventListener('click', function() {
serviceworkerRegistrationInstalling.postMessage({
message: document.querySelector('#message').value
});
setStatus('Message posted using ServiceWorkerRegistration.installing');
});

document.querySelector('#send-message-controller').addEventListener('click', function() {
navigator.serviceWorker.controller.postMessage({
message: document.querySelector('#message').value
});
setStatus('Message posted using navigator.serviceWorker.controller');
});

document.querySelector('#message').value = 'It is now '+new Date().toLocaleTimeString();
document.querySelector('#commands').style.display = 'block';
}

if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./service-worker.js', {scope: './'}).then(function(registration) {
// Registration was successful.

if (registration.installing) {
// If ServiceWorkerRegistration.installing is set, then this page isn't actively controlled
// by a Service Worker, but one was just installed.
document.querySelector('#status').textContent =
'Service Worker was just installed. We can call postMessage using registration.installing';
// We'll use registration.installing to post messages.
serviceworkerRegistrationInstalling = registration.installing;
// Disable button for sending a message using navigator.serviceWorker.controller
document.querySelector('#send-message-controller').disabled = true;
} else if (navigator.serviceWorker.controller) {
// If .controller is set, then this page is being actively controlled by the Service Worker.
document.querySelector('#status').textContent =
'Service Worker is already controlling this page. We can call postMessage using navigator.serviceWorker.controller';
// We'll use navigator.serviceWorker.controller to post messages.
// Disable button for sending a message using ServiceWorkerRegistration.installing
document.querySelector('#send-message-registration').disabled = true;
}
// Show the interface for sending messages to the Service Worker.
showCommands();
}).catch(function(error) {
// Something went wrong during registration. The service-worker.js file
// might be unavailable or contains a syntax error.
document.querySelector('#status').textContent = error;
});
} else {
// The current browser doesn't support Service Workers.
var aElement = document.createElement('a');
aElement.href = 'http://www.chromium.org/blink/serviceworker/service-worker-faq';
aElement.textContent = 'Service Workers are not supported in the current browser.';
document.querySelector('#status').appendChild(aElement);
}
</script>

<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-53563471-1', 'auto');
ga('send', 'pageview');
</script>
<!-- Built with love using Web Starter Kit -->
</body>
</html>
17 changes: 17 additions & 0 deletions service-worker/install-time-post-message/service-worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/*
Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Simple event listener for logging incoming messages to the console.
self.addEventListener('message', function(event) {
console.log('Message received: ' + event.data.message);
});