I'm writing an extension to demonstrate the use of messages. Here's the idea.
There is an HTML page with a mytext text field and a popup page that also contains a mytext field.
Both text fields are always synchronized in content.
Direct messages between the popup page and the content page do not work. Therefore, all communication takes place through an intermediary - the background page.
Messages are passed between the popup page and the background page via port.postMessage. The background page and content page communicate via chrome.runtime.sendMessage and chrome.tabs.sendMessage.
background.js
let popup_port;
debugger;
chrome.extension.onConnect.addListener(function (port)
{
popup_port = port;
popup_port.onMessage.addListener(function (msg)
{
chrome.tabs.query(
{
currentWindow: true,
active: true
},
function (tabs)
{
// This is where the error occurs.
chrome.tabs.sendMessage(tabs [0].id, msg);
});
return true;
});
});
chrome.runtime.onMessage.addListener(function (msg)
{
popup_port.postMessage(msg);
});
content.js
debugger;
chrome.runtime.onMessage.addListener(function (msg)
{
if (msg.query)
chrome.runtime.sendMessage(mytext.value);
else
mytext.value = msg.input;
});
popup.js
let port = chrome.extension.connect({name: '...'});
debugger;
port.postMessage({query: true});
port.onMessage.addListener(function (textMsg)
{
mytext.value = textMsg;
});
function postMyMessage ()
{
port.postMessage({input: mytext.value});
}
mytext.oninput = postMyMessage;
When I open a popup window, everything works correctly - the text from the main page also appears in the field of the popup page.
But when I enter text into the field from the popup page, an error occurs in the background page:
TypeError: Cannot read property 'id' of undefined
When I tested my code while writing this post, it (suddenly!!!) worked correctly - when I enter text in the popup, it appears in the main page as well. What was it !?