MrRoth MrRoth - 1 month ago 19
Javascript Question

Chrome extension - retrieving Gmail's original message

I am working on an extension for Chrome. I wish parse the content of the "original" Gmail message (the currently viewed message).

I am familiar with programmatically click Gmail's "show original" button in a chrome extension?. But since it does not reveal much information, it is hard to understand it.

I tried to utilize the jQuery.load() as follows

$(windows).load(function() { alert(GLOBALS); });


and place it at the content script, but it does not work either. I am using Chrome's developer tools, which returns the following error on the invocation of the
alert(GLOBALS);


Uncaught ReferenceError: GLOBALS is not defined


although, when using the developers tools' console, typing into the console
GLOBALS
it returns an array. Any clue how can to programatically read the content of the original message? or how to access the GLOBALS from the content script?

Answer

Content scripts run in an isolated environment. To get access to the any global properties (of the page's window), you have to either inject a new <script> element, or use event listeners for passing data.

See this answer for example on injecting a <script> element in the context of the page.

Example

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

var s = document.createElement('script');
s.src = chrome.extension.getURL('script.js');
(document.head||document.documentElement).appendChild(s);
s.onload = function() {
    s.parentNode.removeChild(s);
};

// Event listener
document.addEventListener('RW759_connectExtension', function(e) {
    // e.detail contains the transferred data (can be anything, ranging
    // from JavaScript objects to strings).
    // Do something, for example:
    alert(e.detail);
});

script.js - Located in the extension directory:

setTimeout(function() {
    /* Example: Send data to your Chrome extension*/
    document.dispatchEvent(new CustomEvent('RW759_connectExtension', {
        detail: GLOBALS // Some variable from Gmail.
    }));
}, 0);

Since it is being loaded via a chrome: URL from within the DOM, script.js must be added to the web_accessible_resources section of the manifest file.

Comments