Search code examples
javascriptgoogle-chromegreasemonkeyuserscripts

Chrome iframe parent is undefined


I have this script for Gmail. It runs inside the canvas_frame iframe.
I want to get a handle to the parent document, using parent.document. But in Chrome tells me that it's undefined. Works fine in Firefox, but blows up on Chrome.
So how exactly do I get a handle to the parent document, from within an iframe, in Chrome.
Chrome ver: 11.0.686.3

Here's the code that's failing:

function init() {
    try {
        if(parent == null) {
            console.log(typeof parent);
            window.setTimeout(init, 200);
            return;
        }
        // SOME MORE STUFF
    } catch(e) { console.log(e) }
}

This part just outputs undefined endlessly in the log window.
Here's a test script that produces the same result. It outputs undefined followed by cQ endlessly.

// ==UserScript==
// @name           TEST SCRIPT FOR CHROME
// @version        1.0
// @namespace      1nfected
// @description    TEST
// @include        http://mail.google.com/*
// @include        https://mail.google.com/*
// ==/UserScript==

(function() {
if(document.documentElement.className != 'cQ') {
    console.log('not our frame');
    return;
}
function init() {
    if(window.parent == null) {
        console.log(typeof window.parent);
        console.log(document.documentElement.className);
        window.setTimeout(init, 1000);
        return;
    }
    console.log('Found the parent');
}
init();
})();

Solution

  • I finally realised that in Google Chrome, userscripts are denied access to window.parent .
    It would only work if I injected the script into the webpage.