Created
October 5, 2013 18:48
-
-
Save aldomendez/6844694 to your computer and use it in GitHub Desktop.
Notifications API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Step 1: Check for Notifications API support | |
// check for notifications support | |
// you can omit the 'window' keyword | |
if (window.webkitNotifications) { | |
console.log("Notifications are supported!"); | |
} | |
else { | |
console.log("Notifications are not supported for this Browser/OS version yet."); | |
} | |
// Step 2: Let the user grant permissions to a website to show notifications. | |
document.querySelector('#show_button').addEventListener('click', function() { | |
if (window.webkitNotifications.checkPermission() == 0) { // 0 is PERMISSION_ALLOWED | |
// function defined in step 2 | |
window.webkitNotifications.createNotification( | |
'icon.png', 'Notification Title', 'Notification content...'); | |
} else { | |
window.webkitNotifications.requestPermission(); | |
} | |
}, false); | |
// Step 3: Attach listeners and other actions | |
document.querySelector('#show_button').addEventListener('click', function() { | |
if (window.webkitNotifications.checkPermission() == 0) { // 0 is PERMISSION_ALLOWED | |
// function defined in step 2 | |
notification_test = window.webkitNotifications.createNotification( | |
'icon.png', 'Notification Title', 'Notification content...'); | |
notification_test.ondisplay = function() { ... do something ... }; | |
notification_test.onclose = function() { ... do something else ... }; | |
notification_test.show(); | |
} else { | |
window.webkitNotifications.requestPermission(); | |
} | |
}, false); | |
// Examples | |
// Retrieve tweets using jsonp. | |
var script = document.createElement("script"); | |
script.src = 'http://twitter.com/statuses/user_timeline/'+ username+'.json?' + | |
'count=3&callback=fetchTweets'; | |
document.body.appendChild(script); | |
function fetchTweets(data) { | |
var tweet; | |
var i = data.length; | |
while (i--) { | |
tweet = data[i]; | |
if (window.webkitNotifications.checkPermission() == 0) { | |
window.webkitNotifications.createNotification( | |
tweet.user.profile_image_url, tweet.user.name, | |
tweet.text).show(); // note the show() | |
} else { | |
// Note that we can't call requestPermission from here as we are in the | |
// callback function and not triggered just on user action | |
console.log('You have to click on "Set notification permissions for this page" ' + | |
'first to be able to receive notifications.'); | |
return; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment