首页 > 解决方案 > 如何在当前选项卡上运行 chrome 扩展内容脚本

问题描述

我有一个 chrome 扩展,它传递如下信息: 1. content.js 分析页面并将结果发送到 background.js 2. popup.js 从 background.js 查询结果并将其显示在 popup.html 中。

预期行为:用户每次点击弹出按钮时,都会看到当前标签页的分析数据。

当前行为:每次用户单击弹出按钮时,他都会看到它分析的第一个选项卡的分析数据。

我尝试使用 chrome.tabs.query,但我没有弄清楚。去这里的路是什么?

Content.js(将 DOM 发送到后台)

var fromDOM = new XMLSerializer().serializeToString(document);
console.log(fromDOM);

chrome.runtime.sendMessage({method:'setTitle',title:fromDOM});

Background.js(内容和弹出窗口之间的代理)

var title;
chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
  if(message.method == 'setTitle')
    title = message.title;
  else if(message.method == 'getTitle')
    sendResponse(title);
});

popup.js(显示 DOM)

chrome.runtime.sendMessage({method:'getTitle'}, function(response){
    document.querySelector("p").textContent = response;
  });  

显现

{
    "manifest_version": 2,
    "name": "B",
    "version": "0.1",
    "options_page": "options.html",
    "background" : {
        "scripts": ["background.js"]
    },
    "permissions": [
        "storage",
        "tabs"
    ],

    "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "popup.html"
    },

    "content_scripts": [
        {
            "matches": [
                "<all_urls>"
            ],
            "js": ["content.js"],
            "run_at": "document_end"
        }
    ]

}

标签: google-chrome-extension

解决方案


推荐阅读