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:
var s = document.createElement('script'); s.src = chrome.extension.getURL('script.js'); (document.head||document.documentElement).appendChild(s);
Once the script loads, remove it for cleanliness:
s.onload = function() { s.remove(); };
document.addEventListener('RW759_connectExtension', function(e) { // e.detail contains transferred data, e.g., GLOBALS });
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 });
script.js ("run_at": "document_end" in manifest):
setTimeout(function() { document.dispatchEvent(new CustomEvent('RW759_connectExtension', { detail: GLOBALS // Send data })); }, 0);
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!