chrome.runtime.sendMessage not working in Chrome Extension

后端 未结 2 870
名媛妹妹
名媛妹妹 2021-01-04 13:01

I am trying to create a new extension. I was able to use the chrome.runtime.sendMessage function a while back but right now, I have tried everything and it still is not able

相关标签:
2条回答
  • 2021-01-04 13:18

    Per the text at the end of https://developer.chrome.com/extensions/messaging#simple if you return true from onMessage handler in background.js then you can call sendResponse asynchronously.

    0 讨论(0)
  • 2021-01-04 13:29

    You need to change your code so that in the background.js you must change the behaviour:

    console.log("Atleast reached background.js")
    chrome.runtime.onMessage.addListener (
        function (request, sender, sendResponse) {
            console.log("Reached Background.js");
            if (request.Message == "getTextFile") {
                console.log("Entered IF Block");
                $.get("http://localhost:63342/Projects/StackOverflow/ChromeEXT/helloWorld1", function(response) {
                    console.log(response);
    
                    // to send back your response  to the current tab
                    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
                        chrome.tabs.sendMessage(tabs[0].id, {fileData: response}, function(response) {
                            ;
                        });
                    });
    
    
                })
            }
            else {
                console.log("Did not receive the response!!!")
            }
        }
    );
    

    While for the contentscript you need to do:

    console.log("Hello World!s");
    $(document).ready(function() {
        console.log("DOM READY!");
        $(document.documentElement).keydown(function (e) {
            console.log("Key Has Been Pressed!");
            chrome.runtime.sendMessage({Message: "getTextFile"}, function (response) {
                ;
            })
    
        })
    });
    
    
    // accept messages from background
    chrome.runtime.onMessage.addListener (function (request, sender, sendResponse) {
        alert("Contents Of Text File = " + request.fileData);
    });
    

    The sendResponse can be used as an immediate feedback not as a result of computation.

    0 讨论(0)
提交回复
热议问题