I'm trying to make the most simple Chrome extension ever, but alas, I'm having big issues, would appreciate some help.
This is what I want it to do:
I select some text on a page and press the extension popup. When I do that, the background-color of the selected text is changed to yellow. When I click somewhere else (and the text is deselected) the background-color is removed.
How do I do that?
I found this code around here:
function makeEditableAndHighlight(colour) {
var range, sel = window.getSelection();
if (sel.rangeCount && sel.getRangeAt) {
range = sel.getRangeAt(0);
}
document.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
// Use HiliteColor since some browsers apply BackColor to the whole block
if (!document.execCommand("HiliteColor", false, colour)) {
document.execCommand("BackColor", false, colour);
}
document.designMode = "off";
}
function highlight(colour) {
var range, sel;
if (window.getSelection) {
// IE9 and non-IE
try {
if (!document.execCommand("BackColor", false, colour)) {
makeEditableAndHighlight(colour);
}
} catch (ex) {
makeEditableAndHighlight(colour)
}
} else if (document.selection && document.selection.createRange) {
// IE <= 8 case
range = document.selection.createRange();
range.execCommand("BackColor", false, colour);
}
}
I don't really know how to work the background.js and the popup.js and the context_script.js .
I tried putting this code in the popup.js and calling it with highlight('yellow')
but it didn't work. I also tried putting this code in the background.js and calling it from the popup.js with chrome.extension.getBackgroundPage().highlight('yellow');
but it didn't work.
In any case, even if this code works, it just changes the background-color of the selected text, but does not remove it when the text is de-selected.
In any case, just getting this first bit to work would be a great help.
In its current form, the code works like this: http://jsfiddle.net/LPnN2/12/ The problem is getting it to work with an extension.
This is my manifest.json:
{
"background": {
"scripts": [ "readit.js"]
},
"description": "Reads out selected text",
"icons": {
"128": "icon128.png",
"16": "icon16.png",
"48": "icon48.png"
},
"browser_action": {
"default_icon": "icon48.png",
"default_popup": "popup.html"
},
"content_scripts": [ {
"js": [ "inject.js" ],
"matches": [ "\u003Call_urls\u003E", "https://*/*" ]
} ],
"manifest_version": 2,
"name": "Speak Me",
"options_page": "options.html",
"permissions": [ "contextMenus", "tabs", "notifications", "background" ],
"update_url": "http://clients2.google.com/service/update2/crx",
"version": "0.1"
}
I already have the extension doing something else (using TTS to read-out loud selected text via an API, but would love the text to also be higlighted, hence why I'm trying to implement this).