简体   繁体   English

Chrome扩展程序:sendMessage不起作用

[英]Chrome extension: sendMessage doesn't work

I've already read the documentation from Google on 'message passing' a few times and have probably looked at over 10 other questions with the same problem and already tried quiet a few variations of most of their "solutions" and of what I have below... This is black magic, right? 我已经阅读了谷歌关于“消息传递”的文档几次,并且可能已经查看过10个其他问题同样的问题,并且已经尝试过安静一些大多数“解决方案”的变体以及我在下面的内容......这是黑魔法吧? Either way, here it goes. 无论哪种方式,它都在这里。

Manifest File: 清单文件:

{
    "manifest_version" : 2,
    "name" : "Message Test",
    "version" : "1.0",

    "browser_action": { 
        "default_popup": "popup.html"
    },

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

    "content_scripts": [
        {
        "matches" : ["<all_urls>"],
        "js": ["message-test.js"]
        }
    ]    
}

I'm aware extensions aren't suppose to use inline JS, but I'm leaving this in so the original question can be left as it was since I still can't get the message to send from the background page, When I switch from the popup to the background, I removed the appropriate lines from the manifest.json 我知道扩展不是假设使用内联JS,但是我将其保留在原来的问题可以保留原来的问题因为我仍然无法从后台页面发送消息,当我切换时从弹出窗口到后台,我从manifest.json中删除了相应的行

popup.html file: popup.html文件:

<html>
  <head>
    <script>
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello", theMessage: "Why isn\'t this working?"}, function(response) {
        console.log(response.farewell);
      });
    });
    </script>
  </head>
<body>
</body>
</html>

OR 要么

background.js file: background.js文件:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
  chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello", theMessage: "Why isn\'t this working?"}, function(response) {
    console.log(response.farewell);
  });
});

message-test.js file: message-test.js文件:

var Mymessage;
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    if (message.greeting == "hello"){
        Mymessage = message.theMessage;
        alert(Mymessage);
    }
    else{
        sendResponse({});
    }
});

I get an undefined alert... 我得到一个未定义的警报......

I'm also trying to execute this after pressing a button from a popup and having a window at a specified url, but that's a later issue. 我也试图在弹出一个按钮并在指定的URL上有一个窗口后执行此操作,但这是后来的问题。 The other files for the button and window can be found here except with the background.js content wrapped in an addEventListener("click"....: http://pastebin.com/KhqxLx5y AND http://pastebin.com/JaGcp6tj 按钮和窗口的其他文件可以在这里找到,除了background.js内容包含在addEventListener中(“点击”....: http//pastebin.com/KhqxLx5yhttp://pastebin.com/ JaGcp6tj

There are several issues in your code. 您的代码中存在几个问题。

Chrome doesn't allow inline scripts in extensions. Chrome不允许扩展中的内联脚本。 You must divide your popup.html to script + HTML: 您必须将popup.html划分为脚本+ HTML:

// popup.html
<html>
<body>
<script type="text/javascript" src="popup.js"></script>
</body>
</html>

// popup.js
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    var tab = tabs[0];  // do not forget to declare "tab" variable
    chrome.tabs.sendMessage(tab.id, {
        greeting: "Can you hear me?"
    }, function(response){});
});

Careful reading of this answer may help you. 仔细阅读这个答案可能对您有所帮助。 Every point there applies to your problem. 每个点都适用于您的问题。

Your problem is in when your main script is executing, and when your content scripts are. 问题在于您的主脚本执行时以及内容脚本何时出现。 You need to ensure there is a content script listening before you send a message to it, in worst case injecting it programmatically. 您需要确保在向其发送消息之前监听内容脚本,在最坏的情况下以编程方式注入它。

And to get it working in a popup, follow KAdot's answer . 为了让它在弹出窗口中工作,请按照KAdot的回答

Here is the solution, using background script: 以下是使用后台脚本的解决方案:

manifest.json 的manifest.json

{
    "manifest_version" : 2,
    "name" : "Message Test",
    "version" : "1.0",

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

    "content_scripts": [
        {
        "matches" : ["<all_urls>"],
        "js": ["message-test.js"]
        }
    ]
}

message-test.js 消息test.js

var port = chrome.runtime.connect();
port.onMessage.addListener(function(message, sender, sendResponse) {
    if (message.greeting == "Can you hear me?"){
        alert("Test");
    }
    else{
        sendResponse({});
    }
});

popup.js popup.js

chrome.runtime.onConnect.addListener( function ( port ) {
port.postMessage({
        greeting: "Can you hear me?"
    });
});

Some explanaition: first we are connecting to our background script from content script and then background script sends message to content script. 一些解释:首先我们从内容脚本连接到我们的后台脚本,然后后台脚本将消息发送到内容脚本。

Update 更新

I've improved answer according to @Xan remark. 我根据@Xan评论改进了答案。 But the idea is the same, first of all you should let know your background script of the existence of content script. 但是这个想法是一样的,首先你要知道你的后台脚本是否存在内容脚本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM