1

manifest,json

{
"background": {
    "scripts": ["jquery-3.2.1.min.js", "background.js"]
},
"content_scripts": [{
    "all_frames": true,
    "run_at": "document_start",
    "matches": [
        "http://*/*",
        "https://*/*",
        "file:///*"
    ],
    "css": ["mystyles.css"],
    "js": ["jquery-3.2.1.min.js", "myscript.js"]
}],
"permissions": [
    "<all_urls>",
    "contextMenus",
    "storage",
    "clipboardWrite",
    "clipboardRead",
    "activeTab",
    "identity",
    "webRequest",
    "webRequestBlocking"
],
"web_accessible_resources": [
    "*.png"
]}

content script

chrome.runtime.onMessage(function(message, sender, sendResponse){
console.log(message);});

chrome console

in chrome console

my chrome version : 58.0.3029.110 (64-bit) why chrome.runtime.onMessage is undefined in content_script? Please tell me how to solve this problem~:)

Whether there are other ways to achieve that background sendMessage to content script?

wOxxOm
  • 65,848
  • 11
  • 132
  • 136
Cyrus
  • 13
  • 3

1 Answers1

3

chrome.runtime.onMessage is not a function indeed, it's an Event object that provides addListener function method:

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
  ...
});
wOxxOm
  • 65,848
  • 11
  • 132
  • 136
  • thanks! I tried to use `chrome.runtime.onMessage.addListener`.The Console is not throw error again,but it looks like no effect.Content script is still not accepted message from background script – Cyrus Jun 04 '17 at 09:54
  • Content scripts aren't reloaded automatically when you reload your extension so you need to reload the tab. – wOxxOm Jun 04 '17 at 09:55
  • I'm sure I've done it.but it still no effect.Can you give me some examples of what you realized? – Cyrus Jun 04 '17 at 10:03
  • There are tons of examples. Simply debug the content script and the background page in devtools. – wOxxOm Jun 04 '17 at 10:05
  • 2
    onMessage is still undefined for me ( – SuperUberDuper Dec 02 '17 at 10:09
  • Had the same issue... complete restart of chrome did the trick – Juergen Riemer Mar 18 '19 at 07:59
  • I'm showing onMessage undefined too. But it's in a script my content script loaded by adding a – Jerinaw Aug 16 '20 at 21:59
  • @Jerinaw it's not a content script but a normal page script so it can't use extension messaging, [more info](/a/9517879). – wOxxOm Aug 17 '20 at 05:23