簡體   English   中英

如何從注入的函數(通過 scripting.executeScript)調用 chrome API 函數?

[英]How to call a chrome API function from an injected function (through scripting.executeScript)?

我通過scripting.executeScript注入了一個函數來遞歸地創建按鈕。 我希望按鈕在單擊后調用 Chrome API 函數(downloads.download) 為了生成按鈕,我做了:

// background.js
chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
    if (changeInfo.status == 'complete') {
        // intended to pass the below download function for it to be run later on <<
        chrome.scripting.executeScript({
            target: {tabId: tabId},
            func: addButtons,
            args: [download]
        })
    }
})

function addButtons(downloadCallback) {
    // get all current posts
    let posts = ...
    
    // add download button to all posts
    for (let i = 0; i < posts.length; i++) {
        ...
        let url = tryQuickUrl(post);
        ...

        let button = document.createElement("button");
        button.innerText = "Download";
        
        // intended to use the callback to the download function below <<<<<
        button.onclick = function() { downloadCallback(url); };

        post.appendChild(button);
    }
}

這里的錯誤是無法序列化download ,但是如果我嘗試不使用任何參數並嘗試通過button.onclick = function() { download(url); };調用該函數button.onclick = function() { download(url); }; ,它給出了Uncaught ReferenceError: download is not defined 如果我嘗試將函數嵌入到匿名函數中:

button.onclick = function() { chrome.downloads.download({ // error here
    url: url,
    filename: "test.jpg"
}); };

這給出了一個錯誤Uncaught TypeError: Cannot read properties of undefined (reading 'download') (所以你不能在這里訪問 API 函數?)。

我如何從注入的腳本中調用chrome.downloads.download 謝謝!

如果將來有人看到這一點,我只需要使用消息傳遞在擴展程序和腳本之間傳遞消息。 我使用了一個監聽器來監聽傳入的消息(來自腳本),並相應地處理它們;

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        console.log(sender.tab ?
            "from a content script:" + sender.tab.url :
            "from the extension"
        );
        
        if (request.request === "downloadUrl") {
            let [result, response] = download(request.url);
            sendResponse({
                success: result,
                response: response,
            });
        }
    }
);

並在單擊按鈕時發送消息。

button.onclick = function() {
  chrome.runtime.sendMessage({
    request: "downloadUrl",
    url: url,
  }, function(response) {
    console.log("WEEE", response.farewell);
  });
};

暫無
暫無

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

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