簡體   English   中英

注入HTML訪問Chrome API和全局變量

[英]Injected HTML accessing the Chrome API and global variables

我正在開發Chrome擴展程序,而且我是該程序的新手。 我正在進行的擴展將HTML側邊欄注入到頁面中,將java腳本函數注入到標題中,然后讓用戶按下側欄上的按鈕來創建/保存我的擴展數據。

但是,當我想保存信息時,我使用localStorage,但是localStorage總是相對於當前網站保存。 如何使用localStorage保存我們的擴展程序?

此外,我想在chrome擴展中使用一些全局javascript變量。 這些屬於哪里? 我知道我目前無法從注入的Javascript訪問它們。

我看過消息傳遞,我遇到了一些麻煩。 我不確定它是如何在注入javascript到頁面標題的范圍內工作的。 我嘗試過這個例子,但我的擴展似乎沒有抓住這個消息。

// This function is called in the injected header javascript.
function sendToExtension() {
    setTimeout(function() {
    console.log('page javascript sending message');
    window.postMessage({ type: 'page_js_type',
        text: "Hello from the page's javascript!"},
        '*' /* targetOrigin: any */);
    }, 10);
}

// This is installed in a background script.
window.addEventListener('message', function(event) {
    console.log('content_script.js got message:', event);
});

您必須使用Chrome的sendMessage函數和onMessage偵聽器。 見下文:

function sendToExtension() {
    console.log('Sending message');
    chrome.runtime.sendMessage({ext: "myExtension"}, function(response) {
      console.log(response.ack);
    });
}

// Listener - Put this in the background script to listen to all the events.
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.ext) {
        console.log('Message received from ' + request.ext);
        sendResponse({ack:'received'}); // This send a response message to the requestor
    }
});

暫無
暫無

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

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