I am working on a Firefox WebExtension which has a popup and uses chrome.storage.local
to store state. So far, I have got it to store data for specific tabs using the tab id.
I would like to reinitialize the local storage if the current tab is reloaded. This is because the extension may have made some changes to the DOM which will be lost if the tab is reloaded; what state it has stored is therefore incorrect.
The initial JavaScript code is called from the popup.
How can I run some code when the page is reloaded?
Thanks
Without more information from you as to exactly what you desire to do, it is difficult to determine the best way to do this. In particular, it is hard to know exactly what situations to which you desire to respond.
It looks like you could use a listener to the
tabs.onUpdated
event. While this fires more often than you actually desire, it does fire on reloading of a page.Below is code that calls a function
completedLoadingURLInTab()
when a URL has been loaded, or reloaded on a page. I've left in a bunch ofconsole.log()
calls as comments which I would normally remove. They can be uncommented to show in the console all the times the event fires. This can be useful to determine exactly the contents of the data received from the event and the sequence of events that fire during various page navigation.Note 1: I found that the
changeInfo
object can be invalid under some circumstances. It was necessary to see if a property existed usinghasOwnProperty()
and then obtain the value from thetabs.Tab
object that is also passed to the event handler.Note 2: The
tabs
permission in manifest.json is required.Given loading the add-on, opening a new tab and doing a bit of navigation (including a few page re-loads), the output in the console could look like:
Alternately, use the
webNavigation
eventsThe
webNavigation
events provide you information directly about web navigation. They will probably provide you with a better solution thantabs.onUpdated
.If you use
webNavigation
events, you will need to experiment to see which combination of events fire for the situations your are concerned about. Most likely this will beCompleted
and/orReferenceFragmentUpdated
.So you can get a feel for what when these events fire, the following code will log to the console all
webNavigation
events: