Creating Chrome extensions can empower you with the ability to modify web page behavior. One such need is to retrieve global variables from the page, like the GLOBALS variable in Gmail messages.
Unfortunately, content scripts run in an isolated environment, preventing direct access to the page's window properties like GLOBALS. jQuery's .load() function fails to retrieve it, resulting in ReferenceErrors. This occurs despite being able to access GLOBALS through the developer tools' console.
To bridge this communication gap, you can employ one of two methods:
1. Script Injection:
Inject a new script element into the page context. This script can retrieve the desired data and pass it back to the content script.
2. Event Listeners:
Use event listeners to pass data between the page and the content script. The content script can listen for custom events fired by the page script with the desired information.
Content Script (run_at: "document_end"):
<code class="js">var s = document.createElement('script'); s.src = chrome.extension.getURL('script.js'); (document.head || document.documentElement).appendChild(s); s.onload = function() { s.remove(); };</code>
Script.js (Injected Script):
<code class="js">setTimeout(function() { document.dispatchEvent(new CustomEvent('RW759_connectExtension', { detail: GLOBALS })); }, 0);</code>
The above is the detailed content of How Can I Access Global Variables in Gmail Messages Using a Chrome Extension?. For more information, please follow other related articles on the PHP Chinese website!