Here is what I have now in a background script:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (tab.url.indexOf("developer.apple.com/reference") != -1 && tab.url.indexOf("?language=objc") == -1) {
var objcURL = tab.url + "?language=objc";
history.back();
}
});
I am entering the if
block properly, but history.back()
doesn't appear to do anything. I've tried history.go(-1)
, and I am positive that I have "history" set in the permissions of my manifest
Is this not possible to do from a background script in a chrome extension?
As Mr. Rebot was saying, the problem is that you are executing the history.back();
in the background script not the tab you want to go back in. A simple work around is to use chrome.tabs.executeScript to run the js in the current tab. So all you need to do is replace history.back();
with chrome.tabs.executeScript(null,{"code": "window.history.back()"});
Also, the history permission allows you to read and write the browser history so you do not need it for this to work. You do however need the following permissions to inject the code: [ "tabs", "http://*/*", "https://*/*" ]
Finally, I have to say use chrome.tabs.executeScript carefully, its not much better than eval() but as long as you don't replace the window.history.back();
with a variable you should be ok. Also, if you want to run the code in a page other than the current page you can replace null with the id of the tab you want to inject the code into. Further documentation can be found on the chrome API page found here.