"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Access Global Variables from Gmail\'s Content Script in a Chrome Extension?

How to Access Global Variables from Gmail\'s Content Script in a Chrome Extension?

Published on 2024-11-13
Browse:478

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:

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

Establishing Event Listeners

Additionally, establish event listeners for data exchange:

document.addEventListener('RW759_connectExtension', function(e) {
    alert(e.detail); // Transfer data, e.g., GLOBALS
});

Script.js Injection

In "script.js" (added to web_accessible_resources in the manifest):

setTimeout(function() {
    document.dispatchEvent(new CustomEvent('RW759_connectExtension', {
        detail: GLOBALS // Send GLOBALS to the extension
    }));
}, 0);

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3