Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome extension not running on back button

I am writing a chrome extension that needs to run every time certain webpages are loaded.

Currently when I first load a page the script runs. However if I then go to another page and click "Back" so it returns to the original page, the script does not run. If I then refresh the page it does run the script.

I suspect this is something to do with chrome not running extensions if it is loading a cached version of the page? (Might be total rubbish).

Currently the manifest file says to "run_at" "document_end".

Anyone have any clue how I can make it run the script even when I open the page by navigating "Back"?

like image 694
Matt Hollands Avatar asked Mar 17 '26 16:03

Matt Hollands


1 Answers

It doesn't run because, like the rest of the scripts on the page, they've already run and potentially altered the content. This behavior is native to browsers and it's called back/forward cache.

You can include a pageshow event listener into your content script. For example:

// contentscript.js

function init () {
  alert('Good soup')
}

window.addEventListener('pageshow', init);

The pageshow event is sent to a Window when the browser displays the window's document due to navigation.

This includes:

  • Initially loading the page
  • Navigating to the page from another page in the same window or tab
  • Restoring a frozen page on mobile OSes
  • Returning to the page using the browser's forward or back buttons
like image 144
fregante Avatar answered Mar 20 '26 06:03

fregante



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!