访问使用window.open打开的窗口的内容

Accessing the content of a window opened with window.open

本文关键字:窗口 window open 访问      更新时间:2023-09-26

我知道我可以访问用window打开的窗口。像这样打开:

var myWindow = window.open('url','uniqueWindowId','argument=value,argument=value')
myWindow.document.getElementById('someId').display = "none";
myWindow.document.getElementsByClassName('someClass')[17].firstChild.style.backgroundColor = "red";
...

但是我有,在调试第三方代码期间,我无法从控制台访问myWindow变量的问题(myWindow仅适用于函数)。是否有任何方法我可以得到窗口,使用其唯一的窗口,从父窗口的javascript控制台?

没有标准函数,但我可以看到一个可能的方法:

function retrievePopupWindowHandle(windowName, callback){
  window.open('javascript:window.opener.handleRetrieved = window;', windowName);
  setTimeout(function(){
     var popupHandle = window.handleRetrieved;
     delete window.handleRetrieved;
     callback(popupHandle);
  }, 1);
}

但请记住,您仍然处于所有安全措施之下,例如相同的协议和来源策略。

不建议这样做,但是可以。

一个快速测试来显示它的工作(由于安全策略,它不会在jsfiddle上工作,在本地创建一个文件并在浏览器中打开它):

<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <button id="b">Create Window</button>
  <button id="b2">Retrieve Handle &amp; Test</button>  
<script>
var popupWindow;
function retrievePopupWindowHandle(windowName, callback){
  window.open('javascript:window.opener.handleRetrieved = window;', windowName);
  setTimeout(function(){
     var popupHandle = window.handleRetrieved;
     delete window.handleRetrieved;
     callback(popupHandle);
  }, 1);
}
document.getElementById('b').addEventListener('click', function(){
  popupWindow = window.open('about:blank', 'popupWindow');
});
document.getElementById('b2').addEventListener('click', function(){
  retrievePopupWindowHandle('popupWindow', function(popup){  
      if(popupWindow == popup)
        alert('Handles Match!');
  });
});
</script>
</body>
</html>