简体   繁体   中英

Injected HTML accessing the Chrome API and global variables

I'm working on a Chrome Extension, and I'm new to the process. The extension I'm working on injects an HTML sidebar into the page, injects java-script functions to the header, then let's the user press the buttons on the sidebar to create/save my extension's data.

However, when I want to save the information, I use localStorage, however, the localStorage always saves with respect to the current website. How can I use localStorage to save with respect to our extension?

Furthermore, I would like to use some global javascript variables in the chrome-extension. Where do these belong? I know I can't currently access them from the injected Javascript.

I've looked into message passing, and I've had some trouble with it. I'm not sure how it works in the scope of injected javascript into a page's header. I've tried working with this example, but my extension doesn't seem to catch the message.

// 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);
});

You have to use Chrome's sendMessage function and onMessage listener. See below:

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
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM