Accessing a global object from script content in chrome extension

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

Since file1.js is included in background.html, I can access the global object on this page. Therefore, there are no problems here.

When an event such as clicking on the extension button is executed, I run the contents of the script using chrome.tabs.executeScript(null, {file: "contentscript.js"});api.

How can I access SomeObject in a text file in this case?

+5
source share
1 answer

Content script script.

script, :

script, 3 4.
, script :

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

.

+14

All Articles