I’m trying to figure out how to write a simple Chrome extension which allows to transliterate web pages from one alphabet to another. Unfortunately Google’s documentation on Chrome extensions is pretty much confusing for a beginner. I’ve seen a lot of similar questions here, f.ex. Replace text in website with Chrome content script extension, but still can’t get it clear. In a trial run I’m trying to replace all “a”‘s in the page with “Z”‘s.
Here’s my Manifest.json:
{
"name": "My Chrome extension",
"version": "0.1",
"browser_action": {
"default_icon": "icon.png"
},
"permissions": [
"tabs", "http://*/*", "https://*/*"
],
"content_scripts": [{
"matches": ["http://*/*", "https://*/*"],
"js": ["myscript.js"]
}]
}
Myscript.js:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(
null, {code:"document.body.innerHTML = document.body.innerHTML.replace(new RegExp("a", "g"), "Z")"});
});
But this fails to work. If I include only one line into Myscript.js:
document.body.innerHTML = document.body.innerHTML.replace(new RegExp("a", "g"), "Z");
then all ‘a’ letters get replaced with ‘Z’ as soon as the page has loaded, but this is not my goal, as I want to get it working only after the extension button is pressed.
Any help will be much appreciated.
You’ve set up your extension to inject your code using a content script. A content script will get injected into any page that matches your matches field. What you want is to only inject the script if they click on your Browser action. For this you can either have a background page that listens for the chrome.browserAction.onClicked event and reacts to it. Or you can have a default page for your Browser Action that injects the code into the page and if your put window.close as part of the script this will stop any popup from occuring and allow you to avoid using a background page (Im big on avoiding using a background page when ever possible).
For an example of the first method, check out this sample….
http://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/extensions/docs/examples/api/browserAction/make_page_red/
And here’s an example of the second method (which is a modified version of the set_page_color sample)…
manifest.json
popup.html
popup.js
injectedCode.js
NOTE
As Rob W points out in the comments
chrome.tabsandchrome.browserActionare not usable in a content script which is why thechrome.browserAction.onClickedhas to be used in a background page.