With my google extension, chrome I want to transfer data from one domain to another. Namely, the text from one site to another. localStorage disappears immediately.

Tried through chrome.tabs.query , chrome.tabs.get , chrome.tabs.create , but it does not work, passes null .

What are the working options so that you can transfer the value from one site to another using your google chrome plugin?

    1 answer 1

    Tabs do not have the ability to communicate with each other directly. To transfer data, you must use the background script as a message broker.

    Expansion example:

    manifest.json

     { "name":"Test", "manifest_version": 2, "description":"", "version":"1.0", "content_scripts": [ { "matches":[ "<all_urls>" ], "js": ["content-script.js"] } ], "background": { "scripts":["background.js"] }, "permissions": [ "tabs", "*://*/*" ] } 

    background.js

     // ΠŸΡ€ΠΎΡΠ»ΡƒΡˆΠΈΠ²Π°Π½ΠΈΠ΅ сообщСний ΠΎΡ‚ всСх Π²ΠΊΠ»Π°Π΄ΠΎΠΊ chrome.extension.onMessage.addListener(function(msg) { /* * msg = {domain, text} */ chrome.tabs.query({ url: msg.domain // маска Π΄ΠΎΠΌΠ΅Π½ΠΎΠ³ΠΎ ΠΈΠΌΠ΅Π½ΠΈ для Π²Ρ‹Π±ΠΎΡ€Π° Π²ΠΊΠ»Π°Π΄ΠΊΠΈ }, function(result) { if(result.length) { var tab = result[0]; // пСрвая найдСнная Π²ΠΊΠ»Π°Π΄ΠΊ chrome.tabs.sendMessage(tab.id, msg.text); } }); }); 

    Here you can use one content script for all tabs.
    In the example below, a tab on the domain yandex.ru sends a message to the tab with the domain google.com.

    Please note that the URL mask is used to indicate how to get it. The chrome.tabs.query method supports this kind of URL-pattern .

    content-script.js

     if(document.location.host.includes('yandex')) { chrome.runtime.sendMessage({ domain: '*://*.google.com/*', text: 'Hello from yandex' }); } // Π’ΠΊΠ»Π°Π΄ΠΊΠ° с google.com ΠΏΡ€ΠΈΠΌΠ΅Ρ‚ сообщСниС chrome.runtime.onMessage.addListener(function(message) { console.log(message); });