Separate in 2 scripts one for the whole site and another one for Stories, something like:
"content_scripts": [
{
"matches": ["*://*.instagram.com/*"],
"run_at": "document_idle",
"all_frames": true,
"js": ["contentScript.js"]
}, {
"matches": ["*://*.instagram.com/stories/*"],
"run_at": "document_idle",
"all_frames": true,
"js": ["storiesScript.js"]
}
],
Being contentScript.js
for all pages *://*.instagram.com/*
and being storiesScript.js
for all pages *://*.instagram.com/stories*
Alternatively you can use the event popstate
inside contentScript.js
to detect address changes with pushState
and replaceState
which is common in the instagram.com
, in that case nay will separate scripts, then do something like inside contentScript.js
:
//Isolado escopo
(function (w, h) {
var pushState = h.pushState,
replaceState = h.replaceState;
h.pushState = function (state, title, url) {
setTimeout(detectChange, 1);
return pushState.call(h, null, title, url);
};
h.replaceState = function (state, title, url) {
setTimeout(detectChange, 1);
return replaceState.call(h, null, title, url);
};
// dispara quando o script é inserido na página
detectChange();
// adiciona o evento popstate para quando o usuário usar back ou foward
w.addEventListener('popstate', detectChange);
function detectChange() {
console.log('troca de URL');
if (location.pathname.indexOf("/stories/") === 0) {
// Execute algo nas páginas de stories, exemplo:
funcoesStories();
} else {
// Execute algo nas outras páginas, exemplo:
outrasFuncoes();
}
}
})(window, history);
And in manifest.json you should only use:
"content_scripts": [
{
"matches": ["*://*.instagram.com/*"],
"run_at": "document_idle",
"all_frames": true,
"js": ["contentScript.js"]
}
],
I used location.pathname
to get the URL PATH and with .indexOf("/stories/") === 0
checks if PATH is /Stories/ or another page inside it.
Note that I rewrote the history.pushState
and history.replaceState
because they don’t fire the event popstate
(details in https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate)
Thank you so much! I knew it was something simple, but I had no idea how to do it. It helped a lot
– Vitor Ceolin
Guilherme, the file doesn’t seem to load if I open the Tories, only if I copy the link and create a new page (I believe it is something related to the page not reload, but only the url change). Any idea what I can do about it?
– Vitor Ceolin
@Vitorceolin updated the answer;
– Guilherme Nascimento
@Vitorceolin updated the code, had forgotten that pushState and replaceState do not fire the popstate, so this way will probably solve for all navigation situations.
– Guilherme Nascimento