首页 > 解决方案 > 如何将消息从 background.js 传递到内容脚本并操作 DOM?

问题描述

我在后台脚本中有一个选项卡更改侦听器,它将检查 URL 并相应地向内容脚本发送消息以进行 DOM 操作。这段代码有什么问题?

我试过 chrome.runtime。以及 chrome.tabs。API。此外,console.log() 在 content.js 中不起作用。

背景.js

chrome.tabs.onActivated.addListener(function(activeInfo) {
    chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
        let arr = tabs[0].url.split('/');
        let url = arr[0] + "//" + arr[2];
        if(url=="https://youtube.com"){
            chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
                chrome.tabs.sendMessage(
                    tabs[0].id, {action: "open_dialog_box"}, function(response) {console.log(response)}
                );  
            });
        }
    });
});

内容.js

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    console.log(request);
    if (request.msg === "youtube_action") {
        //console.log(request.data.subject)
        alert("kdjfnodf");
    }
    return true;
});

清单.json

{
    "manifest_version" : 3,
    "name" : "Play",
    "description" : "Play",
    "version": "2",

    "browser_action" : {
        "default_title" : "Play-Pause",
        "default_popup" : "popup.html"
    },
    "permissions" : [
        "activeTab",
        "tabs",
        "background"
    ],
    "content_scripts": [{
        "matches": ["http://*/*"],
        "js": [
          "content.js"
        ]
    }],
    "background" : {
        "scripts": ["background.js"],
        "persistent": false
    }
}

标签: javascriptgoogle-chrome-extension

解决方案


推荐阅读