Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
742 views
in Technique[技术] by (71.8m points)

javascript - Basic google chrome extension message passing not working

I've been trying to get message passing for a chrome extension to work but console.log(response) gives me undefined. I've looked at the docs for message passing and on stackoverflow, but in my case it won't work. I am at a loss as to why.

myscript.js:

chrome.extension.sendRequest({greeting: "hello"}, function(response) {
    console.log(response);
    return true;
});

background.js:

chrome.runtime.onMessage.addListener(
   function(request, sender, sendResponse) {
      sendResponse({farewell: "goodbye"});
      return true;
 });

manifest.json

{
  "manifest_version": 2,

  "name": "nameasf",
  "description": "asfasaf",
  "version": "1.0",

  "permissions": [
    "tabs",
    "http://somedomain.com/"
  ],

    "content_scripts": [
    {
      "matches": ["http://somedomain.com/*"],
      "css": ["mystyles.css"],
      "js": ["jquery.js", "myscript.js"],
      "all_frames": true
    }
  ],

  "background": {
    "scripts": ["background.js"]
  },

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are using the obsolete chrome.extension.sendRequest.
Use chrome.runtime.sendMessage instead.

(Note: You are already using the new chrome.runtime.onMessage so you don't have to change anything on the listener side.)


A couple of sidenotes:

  • For the code presented here you don't need any permission (especially not the powerful tabs permission).
  • And it is a good idea to use non-persistent background pages (a.k.a. event-pages) whenever possible as they are considerably more resource-friendly.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...