Skip to content

Commit

Permalink
improve example
Browse files Browse the repository at this point in the history
  • Loading branch information
gmetais committed Jun 10, 2016
1 parent 8e1bc69 commit d2987b1
Show file tree
Hide file tree
Showing 10 changed files with 409 additions and 176 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<script src="/swgetheaders-page.js"></script>
<script>
var options = {
logLevel: 2
debug: true
};
swgetheaders.registerServiceWorker('/swgetheaders-worker.js', options);
swgetheaders.on('plugged', function() {
Expand Down
7 changes: 7 additions & 0 deletions examples/assets/justAScript.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
function thatDoesNothing() {
if (1 === 2) {
window.alert('Your browser has a major problem');
}
}

thatDoesNothing();
107 changes: 91 additions & 16 deletions examples/checkGzip.html
Original file line number Diff line number Diff line change
@@ -1,39 +1,114 @@
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<style>
#request, #response {
margin: 5px;
padding: 5px;
width: calc(100% - 10px);
border: 1px solid black;
white-space: pre;
font-family: Consolas;
}
#plugged {
margin: 20px 0;
font-weight: bold;
color: red;
}
</style>
</head>
<body>
<h1>Gzip checker example</h1>
<button onclick="sendCorsRequest()">Send a cross-domain request</button>
<button onclick="sendRequest()">Send a same-domain request</button>
<div id="plugged">The service worker is not fully installed, you need to refresh the page.</div>
<button onclick="requestSameDomain()">Send a same-domain request</button>
<br>
<button onclick="requestCorsAllowNoException()">Send a cross-domain request to a domain with allow-origin and no exception set</button>
<br>
<button onclick="requestCorsAllowException()">Send a cross-domain request to a domain with allow-origin and an exception</button>
<br>
<button onclick="requestCorsNoAllowNoException()">Send a cross-domain request to a domain without allow-origin and no exception set</button>
<br>
<button onclick="requestCorsNoAllowException()">Send a cross-domain request to a domain without allow-origin and an exception</button>
<br>
<img id="googleLogo" src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" />
<img id="localImage" src="exemple-image.jpg" />
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
Request:
<div id="request"></div>
Response:
<div id="response"></div>

<script src="/swgetheaders-page.js"></script>
<script>

// Needed because the library uses browserify
var swgetheaders = require('swgetheaders');
swgetheaders.registerServiceWorker('/swgetheaders-worker.js', {logLevel: 2});

// Register the service worker (with options)
swgetheaders.registerServiceWorker('/swgetheaders-worker.js', {
debug: true,
corsExceptions: [
'code.jquery.com',
'platform.twitter.com'
]
});

// Console log when the service worker is ready to do things
swgetheaders.on('plugged', function() {
console.log('The service worker is now activated and ready to listen to requests');
document.getElementById('plugged').style.display = 'none';
});
swgetheaders.on('request', function(request) {
console.log('A request was just sent:');
console.log(request);
});

// Fill up the request and response divs with the JSON results
swgetheaders.on('response', function(request, response) {
console.log('A response just arrived. We have both the request and the response:');
console.log(request);
console.log(response);

if (swgetheaders.isPlugged() && handMadeRequest) {
document.getElementById('request').innerHTML = JSON.stringify(request, null, 2);
document.getElementById('response').innerHTML = JSON.stringify(response, null, 2);
}
});

function sendCorsRequest() {
document.getElementById('googleLogo').src = 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png?q=' + Date.now();
var handMadeRequest = false;

function requestSameDomain() {
clearFields();
injectScript('assets/justAScript.js');
handMadeRequest = true;
}
function sendRequest() {
document.getElementById('localImage').src = 'exemple-image.jpg?q=' + Date.now();

function requestCorsAllowNoException() {
clearFields();
injectScript('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js');
handMadeRequest = true;
}

function requestCorsAllowException() {
clearFields();
injectScript('https://code.jquery.com/jquery-3.0.0.min.js');
handMadeRequest = true;
}

function requestCorsNoAllowNoException() {
clearFields();
injectScript('https://connect.facebook.net/en_EN/sdk.js');
handMadeRequest = true;
}

function requestCorsNoAllowException() {
clearFields();
injectScript('https://platform.twitter.com/widgets.js');
handMadeRequest = true;
}

function injectScript(url) {
var script = document.createElement('script');
script.src = url + '?q=' + Date.now();
document.body.appendChild(script);
}

function clearFields() {
document.getElementById('request').innerHTML = '';
document.getElementById('response').innerHTML = '';
}

</script>
</body>
</html>
Binary file removed examples/exemple-image.jpg
Binary file not shown.
31 changes: 31 additions & 0 deletions lib/logger.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
var Logger = function() {

var debug = false;

function log(message) {
if (debug) {
console.info(message);
}
}

function error(message) {
console.error(message);
}

function getDebug() {
return debug;
}

function setDebug(value) {
debug = value;
}

return {
log: log,
error: error,
getDebug: getDebug,
setDebug: setDebug
};
};

module.exports = new Logger();
64 changes: 30 additions & 34 deletions lib/page.js
Original file line number Diff line number Diff line change
@@ -1,65 +1,74 @@
var logger = require('./logger');

(function() {
'use strict';

var onPluggedCallbacks = [];
var onRequestCallbacks = [];
var onResponseCallbacks = [];

const LOG_SILENT = 0;
const LOG_ERRORS = 1;
const LOG_WARNINGS = 2;
const LOG_INFO = 3;
var logLevel = LOG_WARNINGS;
var plugged = false;
var corsExceptions = [];

function registerServiceWorker(swPath, options) {
if (options && options.logLevel >= 0) {
logLevel = options.logLevel;
if (options && options.debug !== undefined) {
logger.setDebug(options.debug);
}

if (options && options.corsExceptions !== undefined) {
corsExceptions = options.corsExceptions;
}

if (!('serviceWorker' in navigator)) {
log('[Page] Your browser doesn\'t support service workers', LOG_WARNINGS);
logger.log('[Page] This browser doesn\'t support service workers');
return;
}

if (navigator.serviceWorker.controller) {
if (navigator.serviceWorker.controller.scriptURL.indexOf(swPath) >= 0) {
log('[Page] The service worker is already active', LOG_INFO);
logger.log('[Page] The service worker is already active');
openCommunicationWithWorker();
} else {
log('[Page] The page already has another service worker: ' + navigator.serviceWorker.controller.scriptURL, LOG_ERRORS);
logger.error('[Page] The page already has another service worker: ' + navigator.serviceWorker.controller.scriptURL);
}
return;
}

log('[Page] The service worker needs to be installed');
logger.log('[Page] The service worker needs to be installed');
navigator.serviceWorker.register(swPath)
.then(navigator.serviceWorker.ready)
.then(function (serviceWorkerRegistration) {
log('[Page] The service worker is registered. It will work after the page changes or is refreshed.', LOG_WARNINGS);
logger.log('[Page] The service worker is registered. It will work after the page changes or is refreshed.');
});
}

function openCommunicationWithWorker() {
var messageChannel = new MessageChannel();
messageChannel.port1.onmessage = function(event) {
if (event.data.error) {
log('[Page] Receveived an error message from SW:', LOG_ERRORS);
log(event.data.error, LOG_ERRORS);
logger.error('[Page] Receveived an error message from SW:');
logger.error(event.data.error);
} else {
log('[Page] Received a message from SW:', LOG_INFO);
log(event.data, LOG_INFO);
logger.log('[Page] Received a message from SW:');
logger.log(event.data);

onDataReceivedFromSW(event.data);
}
};
navigator.serviceWorker.controller.postMessage({
type: 'hello',
logLevel: logLevel
debug: logger.getDebug(),
corsExceptions: corsExceptions
}, [messageChannel.port2]);
}

function isPlugged() {
return plugged;
}

function onDataReceivedFromSW(data) {
if (data.type === 'plugged') {
plugged = true;
broadcast(onPluggedCallbacks);
} else if (data.type === 'request') {
broadcast(onRequestCallbacks, data.request);
Expand All @@ -86,28 +95,15 @@
onResponseCallbacks.push(callback);
break;
default:
log('[Page] Unknown event:', LOG_ERRORS);
log(event, LOG_ERRORS);
logger.error('[Page] Unknown event:');
logger.error(event);
break;
}
}

function log(data, criticity = LOG_INFO) {
if (criticity <= logLevel) {
if (criticity === LOG_ERRORS) {
console.error(data);
} else if (criticity === LOG_WARNINGS) {
console.warn(data);
} else if (criticity === LOG_INFO) {
console.info(data);
} else {
console.log(data);
}
}
}

module.exports = {
registerServiceWorker: registerServiceWorker,
on: on
on: on,
isPlugged: isPlugged
};
})();
Loading

0 comments on commit d2987b1

Please sign in to comment.