Suppose that you use a similar solution to send data from a popup to a content-script .
In this case, it can be slightly modified. Below is the self-contained extension code.
For tracking tab updates and storing the data structure, I suggest adding a background script to the extension. Then everything becomes simple enough:
manifest.json
{ "manifest_version": 2, "name": "Test", "version": "1.0", "description": "", "browser_action": { "default_popup": "popup.html" }, "content_scripts": [ { "matches": [ "<all_urls>" ], "js": [ "content-script.js" ], "run_at": "document_end" } ], "background": { "scripts": ["background.js"] } }
popup.html
<input type="text" id="data"> <button id="go">Send</button> <script src="popup.js"></script>
popup.js
const btn = document.querySelector('#go'); const input = document.querySelector('#data'); btn.addEventListener('click', function() { const text = input.value; chrome.tabs.query({active: true, currentWindow: true}, function(foundTabs) { const activeTab = foundTabs[0]; // Отправка текста в content-script chrome.tabs.sendMessage(activeTab.id, {text: text}); // Отправка данных в background-скрипт для сохранения chrome.runtime.sendMessage({ tabId: activeTab.id, text: text }); }) });
content-script.js
const input = document.querySelector('#lst-ib'); // для примера используется поле ввода Google.com chrome.runtime.onMessage.addListener(function(request) { input.value = request.text; });
background.js
// Структура вида "id таба -> какой текст вставить" const observedTabs = new Map(); // Слушаем сообщения из popup.js chrome.runtime.onMessage.addListener(function(request) { const tabId = request.tabId; const text = request.text; // Сохраняет text для таба по id observedTabs.set(tabId, text); }); // Отслеживаем изменения в табах chrome.tabs.onUpdated.addListener(function(tabId, changeInfo) { // Если id таба находится в списке отслеживаемых и вкладка завершила загрузку... if(observedTabs.has(tabId) && changeInfo.status === 'complete') { const text = observedTabs.get(tabId); // ..то отправляем в content-script сообщение с текстом (такое же как и в popup) chrome.tabs.sendMessage(tabId, {text: text}); } }); // Удаляем таб из память в случае, если вкладка закрылась chrome.tabs.onRemoved.addListener(function(tabId) { observedTabs.delete(tabId); });
Note that the data in observedTabs exists before the extension or browser is reloaded. In case you need to have permanent access to the saved data, you can use localStorage or chrome.storage.local .