How to write some javascript in a Chrome extension, so that if the javascript code is run, and the user presses the back button, it goes back twice?

后端 未结 2 858
闹比i
闹比i 2021-01-26 13:43

Basically, in my chrome extension, it creates a redirect on certain pages within a domain. This is indeed the behavior I want it to be doing. I do not want this changed - it is

2条回答
  •  有刺的猬
    2021-01-26 14:24

    Instead of using background pages to modify the history navigation behaviour, avoid the problem by not creating the history entry in the first place.

    For example, by using location.replace in a content script:

    // Running on http://domain.com/page2.html
    location.replace('http://domain.com/page2.html&aaa');
    

    Manifest file:

      "content_scripts": [{
          "matches": ["*://domain.com/page2.html"],
          "js": ["redirect.js"],
          "run_at": "document_start",
          "all_frames": true
      }],
    

    EDIT:
    You alleged that location.replace does not fetch the resource from the server. That's not true. What you're experiencing is that your page was cached by the browser. To make sure that the page is reloaded from the server, use a cache busting method, such as appending a random query string parameter to your URL:

    // Running on http://domain.com/page2.html
    location.replace('http://domain.com/page2.html?aaa&_t=' + new Date().getTime());
    

    In the previous case, you would navigate to http://domain.com/page2.html?aaa&_t=1234.... The value of 1234... is reasonably unique, so the page is never fetched your browser's local cache.

    Do you control the server? If yes, you can also disable the cache through headers. For more information on this subject, see Making sure a web page is not cached, across all browsers.

提交回复
热议问题