0

When I click links on webpages, the script gets executed once, as expected, but when the webpage redirects the user (such as using history.pushState() the script gets executed twice, how can I stop this?

It's mind boggling that the history API doesn't make a difference between redirects and click on links, it reports them both as type link of transitionType.

The executeScript by default only executes on the top frame (frameId 0) so that's not the problem. And I also used frameId and parentFrameId properties of the callback function although I knew it wouldn't fix the problem because as I've said, on clicking links, the script is executed only once, but when the browser redirects, it's executed twice.

BackgroundScript:

chrome.webNavigation.onHistoryStateUpdated.addListener(function(obj){
    if (obj.frameId === 0 && obj.parentFrameId === -1){
        chrome.tabs.executeScript({
            file: 'js/contentScript.js',
            runAt: 'document_end'
        });
        console.log(obj.transitionType);
    }
});

ContentScript:

console.log("executed!");
0

1 Answer 1

1

onHistoryStateUpdated event is triggered not only on the browser back/forward actions but also when the site scripts use window.history methods so it can happen even 1000 times per navigation if the page calls the API that many times, there's no limit.

If the problem here is the multiple execution of the script you can simply send a message first and inject only if no response is received. Or use a global variable in the content script, see how to avoid dynamically injecting the same script multiple times when using chrome.tabs.executeScript.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.