在Google Chrome扩展程序中传递消息

时间:2019-04-26 22:50:54

标签: google-chrome-extension

我正在学习Chrome扩展程序,并且很难理解消息的传递。

为了更好地理解这一点,我有一个按钮,然后单击它会把页面上的内容变成红色,如果有内容可以更新弹出窗口本身的标题。

但是我不断收到错误消息:

“未选中的runtime.lastError:消息端口在收到响应之前已关闭。”

(Chrome扩展程序开发工具内部)

“事件处理程序中的错误:TypeError:无法读取未定义的属性'query'     在chrome-extension://jhpandehcddbmdcjiaioihimniapmpci/content_script.js:8:29“

(在活动页面开发工具上)

有人可以为此指出好的资源或简单的解决方案吗?

manifest.json

{
"manifest_version": 2,
"name": "My ExTeNsIoN",
"version": "1.0",
"description": "My Extension",
"permissions": [
    "tabs","<all_urls>"
    ],
"browser_action": {
    "default_popup": "popup.html"
},
"content_scripts": [{
        "matches": ["http://*/*","https://*/*"],
        "js": ["jquery-3-4-0-min.js", "content_script.js"]
    }]

}

popup.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Extension</title>

<link rel="stylesheet" type="text/css" href="popup.css">
</head>
<body>

<h1 id="the_title"></h1>

<input type="submit" id="color_button" value="Change Color">

<script src="jquery-3-4-0-min.js"></script>
<script src="popup.js"></script>
</body>
</html>

popup.js

   $("#color_button").on("click",function() {
 chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
        console.log("sending hello greeting.");
  });
  });
 })



chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if (request.greeting == "hello_2") {
    $("#the_title").text("This Worked!");      
  }
 });

content_script.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {

  if (request.greeting == "hello") {
    $("p").css("color","#ff0000");

        if($("p")) {

            chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
                chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello_2"}, function(response) {
                    console.log("sending hello_2 greeting.");
            });
          });
        }

    }
});

0 个答案:

没有答案