2

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?

A O
  • 5,516
  • 3
  • 33
  • 68
  • I'm not sure if it is possible in background script but try using content script that will inject a script that will load the previous page. See the related [SO post](http://stackoverflow.com/a/9517879/5995040), this explain how to inject code in a page using a Content script. Hope this helps. – Mr.Rebot Dec 01 '16 at 15:43
  • what if your listener event is not firing at all? – Bekim Bacaj Dec 10 '16 at 04:40

2 Answers2

4

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.

Partial Science
  • 330
  • 2
  • 6
  • Thanks for the perfect answer. Your account history is very interesting.. I'm surprised you came along this old question, but thanks for your time! Saved me a lot of headache – A O Dec 12 '16 at 05:45
  • Since Chrome 72, there is way of doing this without executing a content script: chrome.tabs.goBack(tabId). See this answer: https://stackoverflow.com/a/55947142/855475 – Martin Taleski May 02 '19 at 07:02
3

Since Chrome version 72 (released in January 2019), there are two new methods on the tabs API, goBack() and goForward().

chrome.tabs.goBack(tabId);

https://developer.chrome.com/extensions/tabs#method-goBack

Martin Taleski
  • 6,033
  • 10
  • 40
  • 78