Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

javascript - Accessing global object from content script in chrome extension

I have defined a global object in a .js file. For example file1.js contains the global object SomeObject. This file gets loaded in background.html.

Since file1.js is included in background.html, I am able to access the global object in this page. So no issues here.

When an event like click on the extension button is performed, I am running a content script using the chrome.tabs.executeScript(null, {file: "contentscript.js"}); api.

How can I access SomeObject in the contentscript in this case?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is no way to get direct access to the background page's global object from a Content script or injected script.

To use a background page's method from an injected script , follow these steps:

  1. Content Script: Bind an event listener to the page example 1.
    Whenever you want to notify the method from the background page:
  2. Injected script: Create and fire this specific event example 1.
    → The event listener from 1) gets triggered.
  3. In this event listener, use chrome.runtime.sendMessage to request the functionality from the background example 2.
  4. In the background page, handle this request using chrome.runtime.onMessage.
  5. Optionally, inject code in the original tab using chrome.tabs.executeScript(tab.id, func).

To use a background page's method from a Content script, only steps 3 and 4 are needed.
Here's an example, in which the content script communicates with the background page:

// Example background page
function some_method(arg_name) {
    return localStorage.getItem(arg_name);
}
chrome.runtime.onMessage.addListener(function(request, sender, callback) {
    if (request.type == 'localStorage - step 4') {
        callback( some_method(request.name) );
    } else if (request.type == 'localStorage - step 5') {
        localStorage.setItem(request.name, request.value);
    }
});

// Example contentscript.js
chrome.runtime.sendMessage({
    type: 'localStorage - step 4',
    name: 'preference'
}, function(value) {
    if (value === null) {
        // Example: If no preference is set, set one:
        chrome.runtime.sendMessage({
            type: 'localStorage - step 5',
            name: 'preference',
            value: 'default'
        });
    }
});

See also


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...