Search code examples
javascriptgoogle-chrome-extensioncontent-script

How to access/bind to DOM from content script after page reloads?


I have a chrome extension where the page is reloaded from inside a content script. The content script is being run using chrome.tabs.executeScript() from my popup.js on the currently active tab.

After the reload, I am unable to bind to the scroll event of the window from the content script. Is there a way to recapture the reloaded DOM to bind to the scroll event ?

Update:

popup.js

chrome.tabs.executeScript(null, { file: 'sendArticleLength.js', allFrames: true}, function(result) {
    count = result;                 
    chrome.tabs.reload(targetTabID, function() {
    chrome.tabs.executeScript({file: 'sendRemainingTime.js', allFrames: true}, function(){                  
            chrome.tabs.sendMessage(targetTabID, {wordcount:count});
    });
});

sendRemainingTime.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
    if(request.wordcount) {
        wc = request.wordcount;
        window.onscroll = function(){
            alert('scrolled!');
        }
    }
});

In sendRemainingTime.js, I want to bind to onscroll event after the reload triggered in popup.js finishes. But currently, the onscroll binds before the reload.


Solution

  • Update:

    As the debugging showed the real issue was something else :-) namely, usage of a var location = assignment which actually reloaded the page and the fact that chrome.tabs.reload executes its callback immediately without waiting for the page to actually reload, so chrome.tabs.onUpdated listener solved the issue.