0

I am trying to communicate with a google chrome extension using JavaScript. I have succeeded in calling the extension from my code. But can't read the response back to my application.

I have written the calling function like this.

function extensionCall(){
    var event = document.createEvent('Event');
    event.initEvent('EXTENSION_READ_EVENT');
    document.dispatchEvent(event);
}

And the code inside the extension is

document.addEventListener("EXTENSION_READ_EVENT", function (data) {
    chrome.runtime.sendMessage("test", function (response) {
    });
});
chrome.extension.onMessage.addListener(function (msg, sender, sendResponse) {
    if (msg.action == 'EXTENSION_DATA') {
        try {
            readExtension($.parseJSON(msg.response));
        }
        catch (e) {
            var error = "error" + e;
        }
    }
});

And I am expecting the response here..

function readExtension(val){
    console.log(val);
}

But unfortunately, I am not getting any response from the extension.

How can I access the data to my application?

  • The preferred method is via externally_connectable, see [Sending messages from web pages](https://developer.chrome.com/extensions/messaging#external-webpage). Your current code won't work because `document` listener should be inside the content script whereas onMessage listener should be inside the background script which has a [different console](https://stackoverflow.com/a/10258029). – wOxxOm Oct 03 '20 at 06:10
  • Hi, I had written the listener inside the content script only, and I had added the origins in the manifest.json file too. I can access the data if I am printing the data in an html file in local system. But when I am accessing the extension from another website, "Unchecked runtime.lastError: The message port closed before a response was received." error is coming. – JavaScript Student Oct 03 '20 at 07:38
  • Your question currently is unanswerable. You need to provide a **proper** [MCVE](/help/mcve) with file names and show how those files are declared in manifest.json. – wOxxOm Oct 03 '20 at 08:27

0 Answers0