How to transfer data between the content scripts of two different tabs?

自闭症网瘾萝莉.ら 提交于 2019-12-18 12:47:17

问题


In my extension I need to transfer some data from one tab's content script to another tab's content script. How can I choose certain tab using chrome.tabs, if I know a part of that tab object's name or url in it? How can two tabs' scripts communicate?

UPDATE:

Apparently I don't have method sendMessage in chrome.extension. When I run the following from content script:

chrome.extension.sendMessage("message");

I get in console:

Uncaught TypeError: Object # has no method 'sendMessage'


回答1:


First, note that messages passed within an extension are JSON-serialized. Non-serializable types, such as functions, are not included in the message.

Within a content script, you have to pass the message to the background page, because there is no method to directly access other tabs.

// Example: Send a string. Often, you send an object, which includes
//  additional information, eg {method:'userdefined', data:'thevalue'}
chrome.extension.sendMessage(' ... message ... ');

In the background page, use the chrome.tabs.query method to get the ID of a tab. For the simplicity of the example, I've hardcoded the patterns and urls. It might be a good idea to include the query values from the previous message, in this way: {query:{...}, data:...}.

// background script:
chrome.extension.onMessage.addListener(function(details) {
    chrome.tabs.query({
        title: "title pattern",
        url: "http://domain/*urlpattern*"
    }, function(result) {
        // result is an array of tab.Tabs
        if (result.length === 1) { // There's exactely one tab matching the query.
            var tab = result[0];
            // details.message holds the original message
            chrome.tabs.sendMessage(tab.id, details.message);
        }
    });
});

chrome.tabs.sendMessage was used to pass the original data to a different tab.

Remark: In the example, I only passed the message when the query resulted in one unique tab. When uniqueness is not a prerequisite, just loop through all resulting tabs, using result.forEach or:

for (var i=0, tab; i<result.length; i++) {
    tab = results[i];
    ...
}



回答2:


From a content script you only can communicate with the background process. You may communicate between two content scripts in differents tabs using the backgound as intermediate.

Also the DOM provide other way to communicate between DOM windows, but with the same origin policy...

To get a tab's url, you may execute a content script on it. The content script can get the url using window.location.href



来源:https://stackoverflow.com/questions/11597416/how-to-transfer-data-between-the-content-scripts-of-two-different-tabs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!