簡體   English   中英

為什么我在點擊 chrome 擴展時出現錯誤?

[英]Why am I getting an error when I click chrome extension?

我正在嘗試創建一個簡單的 chrome 擴展。 我能夠加載擴展程序,但是當我單擊地址欄旁邊的擴展程序圖標時,出現錯誤: Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist. Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist. 為什么?

我的manifest.json文件:

{
    "name" : "Test",
    "version" : "0.1",
    "permissions" : ["<all_urls>", "tabs", "activeTab"],
    "content_scripts" : [
        {
            "matches" : ["<all_urls>"],
            "js" : ["content.js"]
        }
    ],
    "background" : {
        "scripts" : ["background.js"]
    },
    "browser_action" : {
        "default_popup" : "popup.html"
    },
    "manifest_version" : 2
}

popup.html :

<html>
    <head>
        <link rel="stylesheet" href="popup.css">
        <script src="popup.js"></script>
    </head>
    <body>
        <button>Click</button>
    </body>
</html>

彈出窗口.js

chrome.tabs.query({active : true, currentWindow : true}, (tabs)=>{
    chrome.tabs.sendMessage(tabs[0].id, {action : "button_click"}, response =>{
        console.log(response);
    })
});

內容.js

chrome.runtime.onMessage.addListener((request, sender, sendResponse)=>{
    if(request.action === "button_click"){
        console.log("You clicked the button");
        sendResponse("success");
    }
})

popup.js工作正常,因為它正在記錄響應,但content.js返回undefined響應。 background.js仍然是空的,所以我排除了它。 這是我第一次深入研究 chrome API,所以我真的很困惑為什么它不起作用。

內容腳本僅在頁面第一次在選項卡中加載時運行,因此當您在 chrome://extensions 頁面上安裝或重新加載擴展時,您還需要重新加載選項卡或明確重新注入腳本 此外,默認情況下,內容腳本在 DOMContentLoaded 之后運行,因此如果頁面仍在加載,它可能仍處於等待注入狀態(您可以告訴它在document_start 處運行)。

請注意,在您的用例中,您可能不需要自動注入的內容腳本,因此您可以刪除content_scripts部分,從permissions刪除<all_urls> ,並切換到即使沒有消息傳遞也可以傳遞數據的程序化注入

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM