Home >Web Front-end >JS Tutorial >How to Access Global Variables from Gmail\'s Content Script in a Chrome Extension?
Accessing Global Variables in Gmail Content Script
You seek a solution to retrieve the GLOBALS variable from the active Gmail message's webpage using a Chrome extension.
Isolation in Content Scripts
Content scripts execute in an isolated environment, preventing direct access to page global variables.
Message Passing Techniques
To overcome this isolation, consider message passing techniques:
Injecting a Script Element
Inject a script element into the page's DOM using the extension URL:
<code class="javascript">var s = document.createElement('script'); s.src = chrome.extension.getURL('script.js'); (document.head||document.documentElement).appendChild(s);</code>
Establishing Event Listeners
Additionally, establish event listeners for data exchange:
<code class="javascript">document.addEventListener('RW759_connectExtension', function(e) { alert(e.detail); // Transfer data, e.g., GLOBALS });</code>
Script.js Injection
In "script.js" (added to web_accessible_resources in the manifest):
<code class="javascript">setTimeout(function() { document.dispatchEvent(new CustomEvent('RW759_connectExtension', { detail: GLOBALS // Send GLOBALS to the extension })); }, 0);</code>
Advantages of Message Passing
Message passing approaches allow for limited extension logic exposure to web pages and access to extended Chrome API functions.
Conclusion
By implementing these techniques, you can effectively access global variables like GLOBALS from your Chrome extension's content script.
The above is the detailed content of How to Access Global Variables from Gmail\'s Content Script in a Chrome Extension?. For more information, please follow other related articles on the PHP Chinese website!