I've written a Google Chrome extension called "Word Welter" which demonstrates typoglycemia.
This extension uses a background script to toggle the word scrambling on and off. However, whilst this works on a web page, if a user turns the functionality on and then browses to a different page (i.e. clicks on a hyperlink in the current page), the Chrome button goes back to it's initial state (although the button's tooltip text say the functionality is still on!) and the scrambling functionality is off. It looks as though my content script is only executed once (i.e. when the toggle is executed).
I want the scrambling functionality to remain active as a user navigates to other pages and I'd hoped my use of the background script would work but it clearly isn't. Anyone know how I can fix this issue?
Note that the scrambling feature worked fine (i.e. for every page a user would navigate to) before I introduced the toggle button. However the toggle button is need as it gets annoying if every page is constantly scrambled!
The background script (background.js) is as follows:
var toggle = false;
chrome.browserAction.onClicked.addListener(function(tab) {
toggle = !toggle;
if(toggle){
chrome.browserAction.setIcon({path: "WordWelterIcon19x19_On.png", tabId:tab.id});
chrome.browserAction.setTitle({title: "Word Welter On"});
chrome.tabs.executeScript(tab.id, {file:"content_script.js"});
}
else{
chrome.browserAction.setIcon({path: "WordWelterIcon19x19_Off.png", tabId:tab.id});
chrome.browserAction.setTitle({title: "Word Welter Off"});
chrome.tabs.executeScript(tab.id, {code:"window.location.reload();"});
}
});
and my manifest.json has the following entry for the background script:
"background": {
"scripts": ["background.js"]
}
Any help is appreciated.
I found a solution to this question myself. I changed the code to:
var toggle = false;
var executeContentScript = function() {
chrome.tabs.executeScript({file:"content_script.js", allFrames : true });
};
chrome.browserAction.onClicked.addListener(function(tab) {
toggle = !toggle;
if(toggle){
chrome.browserAction.setIcon({path: "WordWelterIcon19x19_On.png"});
chrome.browserAction.setTitle({title: "Word Welter On"});
executeContentScript();
chrome.tabs.onUpdated.addListener(executeContentScript);
}
else{
chrome.tabs.onUpdated.removeListener(executeContentScript);
chrome.browserAction.setIcon({path: "WordWelterIcon19x19_Off.png"});
chrome.browserAction.setTitle({title: "Word Welter Off"});
chrome.tabs.executeScript({code:"window.location.reload();"});
}
});
The fix was to add a listener so that the content script would be executed every time the active tab is updated; see the call to:
chrome.tabs.onUpdated.addListener(executeContentScript);
This listener is unregistered when it is again toggled by making a call to "removeListener" :
chrome.tabs.onUpdated.removeListener(executeContentScript);