Document 개체에서 Window 개체를 가져 오는 방법은 무엇입니까?
나는 얻을 수 window.document
있지만 어떻게 얻을 수 document.window
있습니까? 모든 브라우저에서이 작업을 수행하는 방법을 알아야합니다.
Window 개체는 자바 스크립트 계층 구조의 최상위 개체 이므로 창으로 참조하세요.
편집 : JS 노력을 홍보 하기 전에 원래 답변 . Mozilla 개발자 네트워크의 JavaScript 기술 개요 는 다음과 같이 말합니다.
브라우저 환경에서이 전역 개체는 창 개체입니다.
편집 2 : 그의 질문에 대한 저자의 의견을 읽은 후 (그리고 반대표를 얻은 후) 이것은 iframe의 문서 창과 관련이있는 것 같습니다. window.parent 및 window.top을 살펴보고 문서 창을 추론하기 위해 비교할 수도 있습니다.
if (window.parent != window.top) {
// we're deeper than one down
}
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;
}
나는 다음에서 DOCUMENT
토큰 을 주입하기로 결정했습니다 @angular/platform-browser
.
import { DOCUMENT } from '@angular/platform-browser'
그런 다음 부모에 액세스합니다.
constructor(@Inject(DOCUMENT) private document: any) {
}
public ngOnInit() {
// this.document.defaultView || this.document.parentWindow;
}
먼저 명확하게합시다. 이러한 종류의 작업은 프레임, iframe 및 여러 창으로 작업 할 때 종종 필요하므로 "창은 전역 개체 일뿐입니다."는 핸들이없는 다른 창 에서 가져온 문서 만 있으면 만족스럽지 못한 대답입니다 . 당신이있는 하나.
둘째, 안타깝게도 창 개체에 직접 접근하는 방법 은 없습니다 . 간접적 인 방법이 있습니다.
사용할 기본 메커니즘은 window.name입니다. 일부 상위 창에서 창이나 프레임을 만들 때 일반적으로 고유 한 이름을 지정할 수 있습니다. 해당 창 내의 모든 스크립트는 window.name에서 가져올 수 있습니다. 창 밖의 모든 스크립트는 모든 자식 창의 window.name에서 얻을 수 있습니다.
그보다 더 구체적이려면 특정 상황에 대한 더 많은 정보가 필요합니다. 그러나 하위 스크립트가 상위 스크립트와 통신 할 수 있거나 그 반대로 통신 할 수있는 모든 상황에서 항상 이름으로 서로를 식별 할 수 있으며 일반적으로 충분합니다.
참조 URL : https://stackoverflow.com/questions/1338224/how-do-i-get-the-window-object-from-the-document-object
'Development Tip' 카테고리의 다른 글
다른 div 내에서 두 div를 가로로 배치하는 방법 (0) | 2020.12.29 |
---|---|
Xcode : 소스 코드를 직접 수정하는 모든 빌드 전에 스크립트 실행 (0) | 2020.12.29 |
DROP… CREATE 대 ALTER (0) | 2020.12.29 |
JavaScript를 사용하여 F5 및 브라우저 새로 고침 비활성화 (0) | 2020.12.29 |
압축 및 암호화 할 때 먼저 압축해야합니까, 아니면 먼저 암호화해야합니까? (0) | 2020.12.29 |