17

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 to send the message to the background script. The console is getting populated with the log messages from the content-script.js but not from the background.js

content-script.js

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) {
                if (response.fileData) {
                    alert("Contents Of Text File = ");
                }
                else {
                    console.log("No Response Received");
                }
            })

    })
});

background.js

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:8000/quicklyusercannedspeechbucket/helloWorld1", function(response) {
                    console.log(response);
                    sendResponse({fileData: response})
                })
            }
            else {
                console.log("Did not receive the response!!!")
            }
        }
    );

manifest.json

{
  "manifest_version": 2,
  "name": "My Cool Extension",
  "version": "0.1",
  "content_scripts": [ {
    "all_frames": true,
    "js": [ "jquery-2.1.4.min.js", "content-script.js" ],
    "matches": [ "http://*/*", "https://*/*", "file://*/*" ]
  } ],
  "permissions": [ "http://*/*", "https://*/*", "storage" ],
  "background": {
    "scripts": [
      "jquery-2.1.4.min.js",
      "background.js"
    ]
  }
}

Any help is appreciated :)

Thanks!

Pranav Jituri
  • 823
  • 1
  • 11
  • 25

2 Answers2

4

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.

gaetanoM
  • 41,594
  • 6
  • 42
  • 61
  • That's it! It worked like a charm. Now, could you please explain why you used the ``chrome.tabs``? I am not able to understand correctly the flow of data from your code sample. Is it like this? Content Script (Generates Event) -> Background Script (Processes Event) -> Background Script (Creates Response Event) -> Content Script (Processes Response Event) ? Isn't there any other way to do this? Sorry to be picky but the documentation provided by Google is not good :( – Pranav Jituri Dec 31 '15 at 20:21
  • 1
    @PranavJituri Usually I write extension so that my background communicates only with the current tab if this tab is of my interest, otherwise I do not inject jquery, js, ....I avoid at all costs to overload Chrome. Yes you understood correctly my flow, and I suggest you to take a look to Chrome Extension [Message Passing](https://developer.chrome.com/extensions/messaging) – gaetanoM Dec 31 '15 at 21:38
  • Thanks a lot mate for explaining the concept behind your code clearly :) – Pranav Jituri Jan 01 '16 at 11:38
1

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.

Moose Morals
  • 1,628
  • 25
  • 32