B
B
BlueOuster2020-09-19 19:16:54
JavaScript
BlueOuster, 2020-09-19 19:16:54

How to pass data from background to content script in chrome extension when navigating to a new page?

I'm writing a chrome extension. We need to catch the url change on the current tab and send some data from the background script to the content script For a simple example, I took the HSE website.
background.js:

chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
    if (changeInfo.url == "https://www.hse.ru/" && changeInfo.status == "complete") {
        var sendObj = {
            "myMessage": "this is main page"
        };
        chrome.tabs.sendMessage(tabId, sendObj);
    } else if (changeInfo.url == "https://www.hse.ru/distant" && changeInfo.status == "complete") {
        var sendObj = {
            "myMessage": "this is some side page"
        };
        chrome.tabs.sendMessage(tabId, sendObj);
    }
});


content.js:
chrome.runtime.onMessage.addListener(function(data) {
    console.log(data.myMessage);
});


It is interesting that on sites where the History API is implemented, that is, pages open without reloading the tab, this code works. If the tab is reloaded when moving to a new address, it no longer works. At first I sinned that the page simply did not have time to load by the time the message was sent to it, but 'changeInfo.status == "complete"' did not help. What am I missing? Thanks in advance for your help.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question