Chrome iframe parent is undefined

醉酒当歌 提交于 2019-12-07 12:12:57

问题


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();
})();

回答1:


UserScripts in Chrome are limited, especially when it comes to iframes.

Any reason why you can't do it the other way? For instance:

var frame = document.getElementById('canvas_frame');
if (frame) {
  var dom = frame.contentDocument;
}

The better answer here would be Chrome Extensions, you would have more control with a Content Script instead of a User Script.




回答2:


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.



来源:https://stackoverflow.com/questions/5211101/chrome-iframe-parent-is-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!