0

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?

Tom McIntyre
  • 3,620
  • 2
  • 23
  • 32
  • Might the prompt interrupt the thread maintaining the port? Simply wrapping the `var input = window.prompt("input please"); port.postMessage({ data: input});` with a setTimeout would suffice, then – Daan Meijer Apr 18 '16 at 13:42
  • Have you tried reading this? http://stackoverflow.com/questions/11782875/chrome-message-passing-error-attempting-to-use-a-disconnected-port-object – Android Enthusiast Apr 19 '16 at 02:05

0 Answers0