Home > Web Front-end > JS Tutorial > How to Access Global Variables from Content Scripts in Chrome Extensions?

How to Access Global Variables from Content Scripts in Chrome Extensions?

Patricia Arquette
Release: 2024-10-26 05:45:02
Original
647 people have browsed it

How to Access Global Variables from Content Scripts in Chrome Extensions?

Accessing Global Variables from Content Scripts in Chrome Extensions

Despite attempts to retrieve the GLOBALS variable from the current Gmail message through jQuery.load() in a content script, errors persist due to isolation.

Solution: Script Injection and Event Listeners

To access global properties of the page's window, consider utilizing:

  1. Script Injection: Injecting a new script element into the page's context:
var s = document.createElement('script');
s.src = chrome.extension.getURL('script.js');
(document.head||document.documentElement).appendChild(s);
Copy after login

Once the script loads, remove it for cleanliness:

s.onload = function() {
    s.remove();
};
Copy after login
  1. Event Listeners: Use event listeners to transfer data:
document.addEventListener('RW759_connectExtension', function(e) {
    // e.detail contains transferred data, e.g., GLOBALS
});
Copy after login

Example Code:

contentscript.js (Run at document_end):

// Inject script
var s = document.createElement('script');
s.src = chrome.extension.getURL('script.js');
(document.head||document.documentElement).appendChild(s);

// Event listener
document.addEventListener('RW759_connectExtension', function(e) {
    alert(e.detail); // Access GLOBALS
});
Copy after login

script.js ("run_at": "document_end" in manifest):

setTimeout(function() {
    document.dispatchEvent(new CustomEvent('RW759_connectExtension', {
        detail: GLOBALS // Send data
    }));
}, 0);
Copy after login

Remember to add "script.js" to the web_accessible_resources section in the manifest file.

Best Practice:

Minimize logic in injected scripts and handle most processing in the content script to ensure extension reliability and access to additional features like chrome.* APIs.

The above is the detailed content of How to Access Global Variables from Content Scripts in Chrome Extensions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template