
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!
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
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
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
Regards,
Write My Essay
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
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
Hello,I love reading through
Hello,I love reading through your blog, I wanted to leave a little comment to support you and wish you a good continuation. Wishing you the best of luck for all your blogging efforts.1z0-238 dumps// BH0-004 dumps// 1Y0-A17 dumps// 1z0-204 dumps// 000-152 dumps// 925-201b dumps// A00-202 dumps// 646-205 dumps//