入手できますwindow.document
が、どうすれば入手できますdocument.window
か?すべてのブラウザでこれを行う方法を知る必要があります。
6 に答える
document.defaultView
ウィンドウであり、IE 9 より前の Microsoft ブラウザーをスキップしても問題ないことが確実な場合は、使用できます。
クロスブラウザソリューションは複雑です。dojoがそれを行う方法は次のとおりです(window.js :: get()から):
// In some IE versions (at least 6.0), document.parentWindow does not return a
// reference to the real window object (maybe a copy), so we must fix it as well
// We use IE specific execScript to attach the real window reference to
// document._parentWindow for later use
if(has("ie") && window !== document.parentWindow){
/*
In IE 6, only the variable "window" can be used to connect events (others
may be only copies).
*/
doc.parentWindow.execScript("document._parentWindow = window;", "Javascript");
//to prevent memory leak, unset it after use
//another possibility is to add an onUnload handler which seems overkill to me (liucougar)
var win = doc._parentWindow;
doc._parentWindow = null;
return win; // Window
}
return doc.parentWindow || doc.defaultView; // Window
has( "ie")は、IEの場合はtrueを返します(それ以外の場合はfalseを返します)。
さて、これが私が行った解決策です。それは機能しますが、私はそれが嫌いです。
getScope : function(element) {
var iframes = top.$$('iframe');
var iframe = iframes.find(function(element, i) {
return top[i.id] ? top[i.id].document == element.ownerDocument : false;
}.bind(this, element));
return iframe ? top[iframe.id] : top;
}
まずはっきりさせましょう。この種のことは、フレーム、iframe、および複数のウィンドウで作業しているときに必要になることが多いため、ハンドルを持っているのがグローバルオブジェクト以外のウィンドウからのドキュメントだけである場合、「ウィンドウは単なるグローバルオブジェクトです」は満足のいく答えではありません。あなたがいるもの。
2 つ目は、残念ながら、window オブジェクトを取得する直接的な方法がありません。間接的な方法があります。
使用する主なメカニズムは window.name です。親ウィンドウからウィンドウまたはフレームを作成する場合、通常は一意の名前を付けることができます。そのウィンドウ内のすべてのスクリプトは、window.name で取得できます。ウィンドウ外のスクリプトは、すべての子ウィンドウの window.name を取得できます。
それよりも具体的にするには、特定の状況に関するより多くの情報が必要です。ただし、子スクリプトが親スクリプトと通信できる場合、またはその逆の場合は、常に名前でお互いを識別できるため、通常はこれで十分です。
Window オブジェクトは JavaScript 階層の最上位オブジェクトであるため、window として参照してください。
編集:JSの取り組み を促進する 前の元の回答。Mozilla Developer Network でのJavaScript テクノロジの概要:
ブラウザー環境では、このグローバル オブジェクトはウィンドウ オブジェクトです。
編集 2: 著者の質問に対するコメントを読んだ後 (および反対票を獲得した後)、これは iframe のドキュメント ウィンドウに関連しているようです。window.parentとwindow.topを見て、それらを比較してドキュメント ウィンドウを推測してください。
if (window.parent != window.top) {
// we're deeper than one down
}