簡體   English   中英

我無法將頁面中的數據發送到擴展程序

[英]I can't send data from the page to the extension

manifest.json

{
    "manifest_version": 3,
    "name": "name",
    "version": "1.0",
    "description": "description",
    "icons": {
        "128": "128.png"
    },
    "action": {
        "default_popup": "index.html"
    },
    "content_scripts": [
        {
            "matches": ["<all_urls>"],
            "js": ["index.js"],
            "css": ["index.css"],
            "run_at": "document_start"
        }
    ],
    "background": {
        "service_worker": "background.js"
    },
    "permissions": ["tabs", "storage", "webRequest", "<all_urls>", "scripting", "storage"]
}

內容.js

browser.runtime.sendMessage({
    name: 'Denis',
});

背景.js

browser.runtime.onMessage.addListener(function (message) {
    console.log(message);
});

我正在從這里做 cntl+c -> cntl+v - 它仍然不起作用......我不知道該做什么以及如何讓它工作,但browser.runtime.onMessage只是不處理要求。

請不要告訴我這是重復的))我已經嘗試了其他帖子中的所有方法進行抄送

在這種情況下,由於頁面接收和發送數據的混淆而發生錯誤。

要將數據發送到擴展,我們需要監聽一個事件以接收文件 content.js(在我的例子中為 index.js)中的數據,而不是發送它們。 要獲取擴展程序中的數據,我們需要將數據發送到登錄頁面,而不是聽取他們的接收。

以不同的方式想象它是合乎邏輯的。 我們需要從着陸頁向擴展發送數據——我們從着陸頁向擴展發送數據:

chrome.runtime.sendMessage()

擴展程序會監聽它們並得到結果:

chrome.runtime.onMessage.addListener()

問題是一切都發生了完全相反的情況,盡管文檔說:

在接收端,您需要設置一個 runtime.onMessage 事件偵聽器來處理消息。 這在內容腳本或擴展頁面上看起來是一樣的。

由於這種混亂,您想知道 - 接收方是什么?

首先,刪除清單文件的權限字段中的所有添加。json,因為在這些示例中不需要它們(它們是出於絕望而添加的)並在 content.js 中重命名 index.js(它將是以這種方式提供更多信息):

{
    "manifest_version": 3,
    "name": "Name",
    "version": "1.0",
    "description": "Description",
    "icons": {
        "128": "128.png"
    },
    "action": {
        "default_popup": "page.html"
    },
    "content_scripts": [
        {
            "matches": ["<all_urls>"],
            "js": ["content.js"],
            "css": ["index.css"],
            "run_at": "document_start"
        }
    ],
    "background": {
        "service_worker": "background.js"
    },
    "permissions": []
}

假設我們想將我們點擊的文本放在擴展中的頁面上。 我們需要在內容file.js中使用非chrome.runtime.SendMessage,它嵌入到登陸頁面並接收DOM數據,我們應該使用chrome.runtime.onMessage,即監聽事件:

內容.js:

// we get the text of the element and save it in the local storage:
document.addEventListener('click', ({ target }) => {
    localStorage.setItem('content', JSON.stringify(target?.textContent));
})

// listening to the response from the extension
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    console.log(request, sender, sendResponse);
    // request - server response
    // sender - extensions id and origin
    // after the response from the extension is received, we send the data directly to extension
    sendResponse(JSON.stringify({ content: localStorage.getItem('content') }));
});

背景.js

// sending data to the current tab
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    console.log(document); // this document will be reference the DOM of your extension, an html file assigned as an action: { default_popup: page.html }
    chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
        // response - this is our sendResponse(JSON.stringify({ content: localStorage.getItem('content') })); from the previous step. this is changing the content in the DOM extension
        document.body.textContent = response;
        // а {greeting: "hello"} - this is our request (response from server) from the previous step
    });
});

不要忘記將 background.js 連接到您的頁面。html(擴展的 html 文件)

在我的例子中,您需要單擊擴展圖標,background.js 觸發 SendMessage 事件並將數據從擴展發送到登錄頁面,其中 content.js 將偵聽此事件並將數據轉發回擴展。 而不是看起來相反。

相反,如果我們需要從擴展中獲取數據,我們不應該在登錄頁面上收聽它們,而是發送它們:

內容.js:

chrome.runtime.sendMessage('Data for extension', function (msg) {
    console.log(msg); // data from extension
});

背景.js:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    console.log(request, sender, sendResponse);
    sendResponse(`From backend: ${request}`); // this will be sent to the landing page (content.js)
});

請記住,在最后一個示例的 background.js 文件中的chrome.runtime.onMessage.addListener中,我們既不是windows也不是document 當您嘗試訪問時,您將得到: Error in the event handler: Link error: Window is not defined 該擴展有自己的控制台。 您需要單擊擴展圖標並右鍵單擊 - 探索。 所有傳入或登錄到擴展程序的數據都將在那里可見。

我討厭這個 API。 我希望我能在這篇文章中幫助某人。

PS我沒有使用polifill

PSS文檔

暫無
暫無

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

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