I am writing a Chrome extension where the extension page communicates with the background page, and also takes some input from the user.
I have something like this:
contentScript.js:
chrome.runtime.onConnect.addListener(function(port) {
if (port.name === "myPort") {
port.onMessage.addListener(function(message) {
if (message.type === "myMessage") {
window.console.log("Received MyMessage");
var input = window.prompt("input please");
port.postMessage({ data: input});
return true;
}
}
port.onDisconnect.addListener(function(arg) {
window.console.log("Port disconnected! ");
window.console.log(arg);
});
}
});
extension.js:
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
let port = chrome.tabs.connect(tabs[0].id, {name: "myPort"});
port.onMessage.addListener(function(data) {
doSomethingWithInput(data.input);
});
port.postMessage({ type: "myMessage" });
});
What I see is the 'Port disconnected!' message as soon as the prompt popup appears. If I comment out the prompt stuff and hardcode the input everything works.
Is this the intended behaviour of Chrome's 'long lived' ports? If so, why? Is there a workaround for what I'm attempting to do?
The API docs describe when a port will be closed here, but it isn't clear to me that any of these will apply. Does a prompt message count as navigating away from the page?