Controlling desktop notifications in chrome extensions

Controlling desktop notifications in chrome extensions
Submitted by carl.blay@suuch.com on Thu, 08/26/2010 - 18:29

So, Google has introduced desktop notifications in chrome extensions for some months now and you bet it's really cool. The notifications are in two flavours : a simple notification and the html variant. The simple one allows you to set the notification's title, icon and content(which is mainly text without html formatting, as it's not allowed), resulting in 'plain' notifications. To really control how the notification looks and stuff it dynamically with content, the way forward is to use the html version. The rest of this post seeks to do just that : creating a custom notification whose content is set dynamically, in this case, with text selected on any web page.
To use notifications without any permission issues, we must request permission in our extension's manifest.json file as follows:

{ //start of json
...
"content_scripts":[
{
"matches":["http://*/*","https://*/*"],
"js":["content.js"]
}
],
"background_page" : "background.html",
....
"permissions":[
....
"notifications",
..
],
...
} //end

The permission has been set with the inclusion of "notifications" under the "permissions" object attribute.Note also, that I have designated content.js as our content script(to be allowed for all http and https domains) and background.html as the background page.

Next, to the content script where text is selected and sent to the rest of the extension.Here goes:

// some gobal variables
var selectedText = "";
var mouseState = new Object(); // monitor state of user's mouse
mouseState.pressed = false;
mouseState.pressedAndMoved = false;
// a function that we'll need to remove both leading and trailing spaces
function trim(word){
return word.replace(/^\s+ | \s +$/g,"");
}
// event handlers on document
document.addEventListener('mousedown',function(event){
mouseState.pressed = true;
mouseState.pressedAndMoved = false;
},false);
document.addEventListener('mousemove',function(event){
if(mouseState.pressed = true && !mouseState.pressedAndMoved){
mouseState.pressedAndMoved = true;
}
selectedText = window.getSelection().toString();
// if selected text is not empty, send it
if(trim(selectedText) != '')
sendWords(selectedText);
}
//function that sends selected text
function sendWords(word){
var port = chrome.extension.connect({name: 'knocking'});
port.postMessage({selected:word});
}

So,we just coded a content script that sends the selected text on the web page to the background page of the extension provided the selected text is not empty.

Now to the background page.The background page, in our case, has the simple task of getting the selected text that was sent by the content script, building a notification and showing the selected text in the notification. Here goes:

var word = "";
//some functions that we need
function formURL(item){
var queryString = "";
queryString += "selection"+ "=" + encodeURIComponent(item);
noticeURL = chrome.extension.getURL('notify.html') + "?" + queryString;
return noticeURL;
}
// add a listener for selected text that has been sent by the content script
chrome.extension.onConnect.addListener(function(port){
if(port.name == 'knocking'){
port.onMessage.addListener(msg){
word = msg.selected; //set selected text to variable 'word'
});
//create HTML notification
var notificationURL = formURL(word);
var notification = webkitNotifications.createHTMLNotification(notificationURL);
notification.show();
});

Some few things to note about the background page code:
The code assumes the name of the notification to be notify.html (we'll actually have to create the file later on)
I passed the selected text (from the content script) to the notification as part of its url as shown by these lines:

var notificationURL = formURL(word);
var notification = webkitNotifications.createHTMLNotification(notificationURL);

This is because the extension and the notification run in different processes. This may not be the only way to get around this but this is surely a way that works :)

Also, the webkitNotifications.createHTMLNotifications() method takes a url as its argument.From the formURL function, we notice that this url is of the form "notify.html?selection=text".This means we should create the notification html page(notify,html) or our function call above would yield an error! To the notification file:


<html>
<head>
<script type="text/javascript" >
//function to get selected text from notification's querystring
function fromQString(){
var selText = [];
var qString = window.location.search;
if(qString.indexOf("?") == 0)
qString = qString.substring(1);
qComponents = qString.split("&");
for(i=0;i,qComponents.length;i++){
qValue = qComponents.split("=");
if(qValue [0]== "selection")
selText.push(decodeURIComponent(qValue[1]));
}
return selText;
}
//function to populate notification with selected text
function populate(){
var content = fromQString();
var target = document.getElementById('content');
target.innerHTML = content;
}
</script>
</head>
<body onload="populate()">
<div id="content" >
</div>
</body>
</html >

For the sake of simplicity and illustration, the above notification page just sets the text passed to it from the extension(background page) as the content one of its child containers;you could however, add some html formatting to it to achieve whichever structure you desire.In addition, you could add some CSS(inline just as the javascript) for aesthetic improvements. However, alerts are not good for the notification's health.
Happy coding!

Its not the case that reader

Its not the case that reader must be completely agreed with author's views about article. So this is what happened with me, anyways its a good effort, I appreciate it. Thanks
afghanistan trademark lawyers

I am building desktop

I am building desktop notification into my a chrome extension that I am working on. The functionality I need required that the user be taken to the tab that caused the notification when they click on the notification window. I can get that working using the chrome.tabs API, but what I can't manage to figure out is how to bring Chrome to the front when the notification is clicked.

I know window.focus() is disabled in chrome, but this is definitely possible to do since that's the behavior of the Gmail desktop notifications. click here

I loved the post a lot. This

I loved the post a lot. This is really great blog, I always find worth reading stuff here. Thanks to writer.

528 LED Strip

Excellent post, I wonder if

Excellent post, I wonder if you can take control of big mind like a group.
plantas aceiteras

If you find it hard to keep

If you find it hard to keep an eye on your tasks, events and other schedules, or may feel regretful of missing your sweetheart’s birthday every year, then worry no more, as ForgetNot! will keep a record of all your important events and tasks. best mobile broadband providers

nice

I am really impressed by this blog! Very clear explanation of issues is given and it is open to everyone.
University Essays
School Essay
Essay Editing
order essay online

great

I am very enjoyed for this side. Its a nice topic. It help me very much to solve some problems. Its opportunity are so fantastic and working style so speedy. I think it may be help all of you.
kombi servisleri

Controlling desktop notifications in chrome extensions

Thanks for the information. Controlling desktop notifications in chrome extensions is something a lot of people have been looking for. warts on hands

awesome topic

Both of those are awesome. I think I like the tracking notifications better with Right Inbox. But the polish on Yesware is amazing. Those posts prompted me to actually right another post (it has been a while)
Cell Phones

nice

This is a fantastic website about iPad3 and iPad4. I can not recommend you guys enough. Full of useful services like iPhone glass replacement and great layout very easy on the eyes.

A very informative article

A very informative article and lots of really honest and forthright comments made ! This certainly got me thinking about this issue, thanks all.
Adult dating

The wallpaper requires proper

The wallpaper requires proper surface preparation before application. Additionally wallpaper is not suitable for all areas. For example, bathroom wallpaper may deteriorate rapidly due to excessive steam. Proper preparation includes the repair of any defects in the drywall or plaster and the removal of loose material or old adhesives. Thanks.
Regards,
reverse email

re

High page rank of PR4 to PR6 of forum profile, Angela Paula style at affordable prices.
Profile linkbuilding

There is no doubt about this

There is no doubt about this article is very very good material.Dubai property for rent

I wanted to thank you for

I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post
Responsibility

Technically speaking desktop

Technically speaking desktop and tower computers are two different styles of computer case that use desk space in varying ways. Cases intended for home theater PC systems are usually considered to be desktop cases in both senses, regardless of orientation and placement. Thanks a lot.
Regards,
desktop wallpapers

nice

Post is nicely written and it contains many good things for me. I am glad to find your impressive way of writing the post. Now it become easy for me to understand and implement the concept. Thanks for sharing the post
sr22 insurance california

This is definitely so amazing

This is definitely so amazing to use. There is much that you can do with it. The options are endless for this. orlando short sale

I wanted to thank you for

I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post
Crescent Processing

This is a good post. This

This is a good post. This post give truly quality information.I’m definitely going to look into it.Really very useful tips are provided here.thank you so much.Keep up the good works.
Crescent Processing

The post is written in very a

The post is written in very a good manner and it entails many useful information for me. I am happy to find your distinguished way of writing the post. Now you make it easy for me to understand and implement the concept. Thank you for the post.

Machine moulin

Medical school personal statement

Medical school personal statement
All of the contents you mentioned in post is just too good that will be extremely helpful. I'll ensure that is stays under consideration, thanks for sharing the details keep updating, impatient for more posts

If you are enrolled in a

If you are enrolled in a school, college or university, you will agree to the fact that term paper writing is one of the most time consuming tasks which at times becomes frustrating too. Dog Life Jacket

wow thats amazing

Fantastic goods from you, man. Ive study your stuff ahead of and you're just as well amazing. I enjoy what you've got right here, adore what you're stating and the way you say it.
PD1-001 dumps
000-667 dumps
MB5-858 dumps
000-201 dumps
E20-522 dumps
412-79 dumps
640-460 dumps
642-746 dumps

This post has helped me for

This post has helped me for writing extensions for Google Chrome. Thank you for giving me another point of view on this topic. Now I can easily complete my article. Gå ner i vikt snabbt Dan

Its really a very interesting

Its really a very interesting posting indeed. Thanks for sharing such interesting posting with us. sngpl duplicate bill

Great work

If you just want to get notified about chat messages, or if you use Priority Inbox and only want to get notifications for important messages, you can customize your settings from there too.
Athletic Apparel | Womens Golf Clothing

I cant ignore this "It's

I cant ignore this "It's great to see a blog of this quality. I learned a lot of new things and I'm looking forward to see more like this."

Regards,
Woodworking Power Tools | Cordless Tools

A comprehensively detailed

A comprehensively detailed and attention grabbing review that you wrote in this article. I am really convinced the way you look. The way you describe the whole thing is simple and understandable

Wow! I really appreciate the

Wow! I really appreciate the thought that you put into this article. This topic has been something I have been looking into for a few hours and your post is one of the best I have read.
Medical Plans

I am glad to say that the

I am glad to say that the admins of this site is really a genius because the material and the design is very good and excellent content he choose to his web.what you think guys?.Dubai free zone | Dubai business set up

Great tips. I’m new to

Great tips. I’m new to article writing and all of the tips help out tremendously, especially Create a savings account and future of family. I always look forward to reading the great advice that is sent to me. Again, it’s excellent advice. Lab Report Help - Assignment

Thanks for sharing .Keep

Thanks for sharing .Keep posting articles like this. A good example of content presentation. A piece of information from you every now and then is really great. Everything was so well coordinated and looked so aesthetically pleasing to the eye. Great job! Custom Research Paper - Custom Term Paper - Custom Thesis

People will not acknowledge

People will not acknowledge this " If you'd like to get into the metallurgical details of some of those steel, see Steel Types.

Regards,
DIY Repair | Tool Parts

I really appreciate details

I really appreciate details you developed. I don't think I've actually considered about it in that way. I can really appreciate how you contacted the person situation and what you said really offered me a new point of view. ged software programs

Resource

We convert your photoshop designs to high quality cross browser compatible, W3C valid and SEO semantic HTML/CSS markup. With over 7 years in business and counting, we understand the intricacies of delivering the best to our customers within the committed turnaround time and at unrivaled quality. PSD to HTML :: Magento Development :: Joomla Developer :: CMS Web Design

Resource

What is affiliate marketing You want to learn affiliate marketing the very best way – step by step? Then you should visit this page. Whether you are a complete and utter newbie or if you are a veteran in this industry, WealthyAffiliate.com has something for you.

Subscribe to fie.nipa by e-mail

Delivered by FeedBurner

©2012 fie.nipa Cooperative