I have a Chrome extension that is limited to an url like this: https://*.example.com/fix-path, however, it would not load when I navigate to the url unless I refresh the page.
I've managed to overcome the issue in two ways, but neither one is good enough and I'd like to understand why it would not work the way I wrote it originally.
Original solution
manifest.json
{
"manifest_version": 2,
"name": "Example",
"version": "1",
"content_scripts": [
{
"matches": [
"https://*.example.com/fix-path"
],
"js": [
"main.js"
],
"run_at": "document_end"
}
]
}
main.js
document.onmousemove = event => {
console.log('hello world');
};
Workaround #1
manifest.json
{
"manifest_version": 2,
"name": "Example",
"version": "1",
"content_scripts": [
{
"matches": [
"https://*.example.com/*"
],
"js": [
"main.js"
],
"run_at": "document_end"
}
]
}
main.js
document.onmousemove = event => {
console.log('hello world');
};
Issues with this solution
Note, that almost everything is the same. The only difference is that I do not limit my script to a specific url, but to the whole domain.
My only problem is that I really need document.onmousemove
, which produces tons of events. It is unnecessary to listen to them on other sub pages.
Workaround #2
Solution borrowed from https://stackoverflow.com/a/21071357/1372608
manifest.json
{
"manifest_version": 2,
"name": "Example",
"version": "1",
"background": {
"scripts": [
"background.js"
]
},
"content_scripts": [
{
"matches": [
"https://*.example.com/fix-path"
],
"js": [
"main.js"
],
"run_at": "document_end"
}
],
"permissions": [
"https://*.example.com/fix-path",
"tabs",
"webNavigation"
]
}
background.js
chrome.webNavigation.onHistoryStateUpdated.addListener(details => {
chrome.tabs.executeScript(null, { file: 'main.js' });
});
main.js
document.onmousemove = event => {
console.log('hello world');
};
Issues with this solution
If I navigate to the https://example.com and then I just click on the menu item to open /fix-path, the extension will load without the need for refresh, however, after this, if I navigate anywhere else, the extension will be loaded. Even the main page will have it loaded once I navigate back.
Conclusion / Final words
It is not the end of the World for me to use either one of these workarounds for neither one is that bad. However, I'd very much want to know why it is not working the way I think it should...
Anyone? : )
UPDATE:
After some fiddling, I've found that the second workaround is almost good.
The issue is that once the main.js is loaded, document.onmousemove
will have a function to call. I somehow have to "delete" this... I have to unload the content script.