簡體   English   中英

Chrome 擴展:從內容到后台腳本的消息傳遞

[英]Chrome Extension: Message Passing from Content to Background Script

我已經搜索並嘗試了從 SO 到這個問題的不同可接受的答案,但它們都不適用於我的情況。 我很確定我不明白一些事情。 我剛剛在 24 小時前開始了這個 chrome 擴展之旅,所以我承認我有很多東西要學。

不過,我正在嘗試為特定網站創建下載器。 我有三個 javascript 文件:

  1. content_scripts中添加的“ script_injection.js ”是一個純 javascript,它調用“ injection_ui.js ”據我所知,我不能直接在 content_scripts 上使用 chrome APIS,所以我創建了另一個 JS 文件並調用它。
  2. injection_ui.js ”,它是“ web_accessible_resources ”的一部分,將按鈕添加到所有圖像並綁定一個功能,以便在單擊時傳遞消息。
  3. background.js ,在后台,監聽按鈕發送的消息。

manifest.json


{
    "name": "Dummy Extension",
    "version": "1.0",
    "manifest_version": 2,

    "description": "This is a dummy extension.",
    "browser_action": {
        "default_title": "Download Images from Anywhere",
        "default_popup": "popup.html"
    },

    "content_scripts" : [
        {  
            "matches": ["https://dummywebsite.com/*"],
            "js": ["script_injection.js"],
            "css": ["style.css"]
        }
    ],

    "permissions": [
        "storage",
        "downloads",
        "activeTab",
        "declarativeContent"
    ],

    "web_accessible_resources": ["injection_ui.js"],

    "background" : {
        "scripts" : ["jquery.js", "background.js"],
        "persistent" : true
    }
}

script_injection.js


var s = document.createElement('script');
s.src = chrome.runtime.getURL('background.js');
s.onload = function() {
    this.remove();
};
(document.head || document.documentElement).appendChild(s);

injection_ui.js

$(document).ready(function(){
    
    $(".image-thumbnail").each(function(){
        var src = $(this).attr("src");
        $(this).append("<a class='DummyAddedButton' download='"+ src +"'>Download</button>");
    }); 

    $(".DummyAddedButton").off().on("click", function(){
        var source = $(this).attr("src");
        
        chrome.runtime.sendMessage("mlbcmjpahokfgkghabmfjgmnafffphpd", source, function(){
            console.log("sending success: " + source);
        });
    });
});

背景.js


chrome.runtime.onMessage.addListener(
    function(message, callback) {
            chrome.downloads.download({url:message, filename:"image.jpg"});
});    

單擊按鈕時,它會在控制台日志上顯示一條由 sendMessage 指示的消息。 但是,它也顯示錯誤: “未檢查的runtime.lastError:無法建立連接。接收端不存在。”

免責聲明。 如果我在 popup.js 上使用相同的按鈕,它會下載圖像。 但我想將功能綁定在網站上注入的按鈕上,而不是通過擴展面板。

當前,您在頁面上下文中注入代碼,這既是不必要的過度復雜化,也是錯誤的,因為您注入的后台腳本已經在與 web 頁面無關的擴展的隱藏單獨背景頁面中運行。 了解如何打開 background.js 開發工具和控制台

從 manifest.json 和 jquery.js 中刪除 script_injection.js、injection_ui.js 和web_accessible_resources部分和不必要的權限。

根據文檔正確聲明 onMessage 偵聽器的參數。

使用"persistent": false , more info

{
  "name": "Dummy Extension",
  "version": "1.0",
  "manifest_version": 2,
  "description": "This is a dummy extension.",
  "browser_action": {
    "default_title": "Download Images from Anywhere",
    "default_popup": "popup.html"
  },
  "content_scripts": [{
    "matches": ["https://dummywebsite.com/*"],
    "js": ["content.js"],
    "css": ["style.css"]
  }],
  "permissions": [
    "storage",
    "downloads"
  ],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  }
}

讓我們使用一個標准名稱 content.js,里面有標准 JS,沒有 jquery。 如果你還想要 jquery,那么在 manifest.json 中聲明為"js": ["jquery.js", "content.js"]

內容.js:

for (const thumb of document.querySelectorAll('.image-thumbnail')) {
  thumb.appendChild(Object.assign(document.createElement('button'), {
    className: 'DummyAddedButton',
    textContent: 'Download',
  }));
}

document.addEventListener('click', e => {
  if (e.target.matches('.DummyAddedButton')) {
    chrome.runtime.sendMessage(e.target.closest('.image-thumbnail').src);
  }
});

背景.js:

chrome.runtime.onMessage.addListener((message, sender, sendMessage) => {
  chrome.downloads.download({url: message, filename: 'image.jpg'});
});    

編輯 manifest.json 或內容腳本后,不要忘記在chrome://extensions頁面和 web 頁面選項卡上重新加載擴展程序。

暫無
暫無

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

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