【问题标题】:send a message from content script to popup script从内容脚本向弹出脚本发送消息
【发布时间】:2020-10-12 11:48:11
【问题描述】:

我正在尝试从我的内容脚本向我的弹出脚本发送一条消息,因为我需要在加载页面时使用弹出 DOM,这是我尝试过的: contentScript.js

window.addEventListener("load", function() {
    chrome.runtime.sendMessage({
        "action": "init"
    });
})

popup.js

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    if (request.action == "init") {
        alert('Initialisation demandée...')
    } else {
        alert('Je n\'ai pas compris')
    }
})

manifest.json

{
    "manifest_version": 2,
    "name": "Youtube color modifier",
    "description": "Change youtube colors",
    "version": "1.0",
    "page_action": {
        "default_icon": "icon.png",
        "default_title": "Youtube color modifier", 
        "default_popup": "popup.html"
    },
    "permissions": [
        "activeTab"
    ],
    "content_scripts": [{
        "matches": ["<all_urls>"],
        "js": ["contentScript.js"]
   }]
}

感谢你帮助一个菜鸟:))

【问题讨论】:

    标签: javascript popup message send content-script


    【解决方案1】:

    如果您有内容脚本,它将在您每次(重新)加载页面时运行,假设您正在访问的页面已在 manifest.json 中注册。

    所以不要这样:

    window.addEventListener("load", function() {
        chrome.runtime.sendMessage({
            "action": "init"
        });
    })
    

    试试这个:

    chrome.runtime.sendMessage({
        "action": "init"
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-03
      • 1970-01-01
      • 2018-04-29
      • 1970-01-01
      • 1970-01-01
      • 2013-07-27
      • 2014-02-04
      相关资源
      最近更新 更多