首页 > 解决方案 > 无法将消息从弹出窗口发送到内容

问题描述

我想通过以下代码将来自 Popup.js 的消息发送到 Content 脚本:

popup.js

chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, { xpath: xpath });
});

并通过以下代码在内容脚本中接收它:

内容.js

chrome.runtime.onMessage.addListener(gotMessage());

function gotMessage(request, sender, sendResponse) {
  alert("Hello");
 
}

我的清单是:

清单.json

    {
  "manifest_version": 2,
  "name": "Auto Clicker",
  "description": "Set Time, Set Element to Click, Start!",
  "version": "0.1",

  "permissions": ["tabs", "<all_urls>"],  
  "browser_action": {
    "default_icon": {
      "16": "images/icon-16x16.png",
      "24": "images/icon-24x24.png",
      "32": "images/icon-32x32.png"
   },
   "content_scripts": [
     {
       "matches": [
         "<all_urls>"
       ],
       "js": ["content.js"]
     }
    ],
    "default_title": "Auto Clicker",
    "default_popup": "popup.html"
  },
  "icons": {
    "16": "images/icon-16x16.png",
    "24": "images/icon-24x24.png",
    "32": "images/icon-32x32.png",
    "128": "images/icon-128x128.png"
  }
}

为什么它不工作?消息不会发送到内容脚本。

标签: google-chromegoogle-chrome-extensioncontent-script

解决方案


我的问题是这样解决的:

// Inject Trigger to the current active Web Page
function injectTheScript() {
  let xpath = document.getElementById("xpath-input").value || "";
  chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
    chrome.tabs.executeScript({
      code: `
      (function () {
        let btn = new XPathEvaluator()
        .createExpression("${xpath}")
        .evaluate(document, XPathResult.FIRST_ORDERED_NODE_TYPE).singleNodeValue;
        btn.click();
       })();
      `
    });
 });
}

推荐阅读