小编use*_*676的帖子

从弹出窗口向内容脚本发送消息 - Chrome扩展程序

我想通过浏览器操作按钮打开它时更新popup.html中的html.popup.js应该向当前选项卡上运行的内容脚本发送消息,并且应该收到响应并更新html.但是,内容脚本不会收到任何消息,因此不会发送正确的响应.

Content.js

var text = "hello";
chrome.runtime.onMessage.addListener(
    function(message, sender, sendResponse) {
        switch(message.type) {
            case "getText":
                sendResponse(text);
            break;
        }
    }
);
Run Code Online (Sandbox Code Playgroud)

Popup.js

chrome.tabs.getCurrent(function(tab){
    chrome.tabs.sendMessage(tab.id, {type:"getText"}, function(response){
        alert(response)
        $("#text").text(response);
    });
});
Run Code Online (Sandbox Code Playgroud)

的manifest.json

{
  "manifest_version": 2,
  "name": "It's Just A Name",
  "description": "This extension is able to",
  "version": "1.0",
  "permissions" : ["tabs"],
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html",
    "default_title": "Click here!"
  },
  "content_scripts": [
  {
    "matches": ["https://*/*"],
    "js": ["jquery.min.js","content.js"]
  }]
}
Run Code Online (Sandbox Code Playgroud)

Popup.html

<!doctype html>
<html>
    <head>
        <title>Title</title>
        <style>
            body {
                font-family: "Segoe UI", …
Run Code Online (Sandbox Code Playgroud)

google-chrome-extension

11
推荐指数
2
解决办法
7402
查看次数

标签 统计

google-chrome-extension ×1