如何使用javascript将焦点返回到父窗口?

时间:2011-08-02 09:58:54

标签: javascript

这不能将焦点返回到Firefox 4和5中的父窗口

<html>
<head>
<script type="text/javascript">
  function openWin()
  {
     myWindow=window.open('','','width=200,height=100');
     myWindow.document.write("<p>The new window.</p>");
     myWindow.blur();
     window.focus();
  }
</script>
</head>
<body>

  <input type="button" value="Open window" onclick="openWin()" />

</body>
</html> 

如何使用javascript将焦点返回到父窗口?

6 个答案:

答案 0 :(得分:13)

您需要为父窗口命名。

Parent.html

<a id="link" href="#">Click to child.html </a>
<script type="text/javascript">
    $(document).ready(function () {
        window.name = "parent";
        $('#link').click(function (event){ 
            event.preventDefault();
            window.open("child.html");
        });
    });
</script>

Child.html

<a id="link" href="#">Return to Parent </a>
<script type="text/javascript">
    $(document).ready(function () {
        $('#link').click(function(event) {
            event.preventDefault();
            var goBack = window.open('', 'parent');
            goBack.focus();
        });
    });
</script>

现在,无论何时单击child.html中的链接,父窗口都将被聚焦。

答案 1 :(得分:3)

很抱歉对一个非常古老的问题进行了解决,但我遇到了同样的问题,但找不到任何解决方案。我最终通过使用以下脚本解决了这个问题:

e = window;
while (e.frameElement !== null) {e = e.parent;}
e.parent.focus();

显然,仅调用window.focus();是不够的。你必须使用window.parent.focus();来调用Window的父焦点方法你不能从它访问JS的任何其他属性,但它会产生跨源错误。如果您的脚本是从页面中的帧触发的,假设框架和主页共享相同的源(域),此脚本也将起作用。

答案 2 :(得分:1)

我不认为你可以返回焦点,而不是关闭子窗口:

myWindow.close()

答案 3 :(得分:1)

我尝试使用上面的示例,但它对我没用。我必须使用递归循环来找到开启者,直到窗口没有开启者(糟糕的设计,我知道,但我们的应用程序有几个级别的子窗口)。这是代码示例。我希望它有所帮助:

/* This is for the button functionality.  
The button element first comes in.  
This element is then used to get the document that has the element.  
The document window opener is then passed to the focusMain method */
function setFocusOnMain(el){
  var doc = el.ownerDocument;
  var win = doc.defaultView || doc.parentWindow;
  focusMain(win.opener.document);
}

/* This is a recursive method that checks for a parent window of the current document.  
If the document has no window opener, focus on this element because this is the Main.  
If the document has a window opener, pass the window opener's document to focusMain. */
function focusMain(doc) {
  var win = doc.defaultView || doc.parentWindow;
  if (win.opener == null)
    doc.focus();
  else
    focusMain(win.opener.document;
}

答案 4 :(得分:0)

以下是我解决这个问题的方法。它在TypeScript中,但您可以轻松编译它JS:

const ParentWindowName = 'ParentWindowName';

// here set the parent window name so that you can switch back to it later and open the new window/tab
export const openChildWindow = (id: string) => {
  (window as any).name = ParentWindowName;
  (window as any).ChildWindowName = window.open(`/child`, id);
};

// here you can change the focus back to the new window.
export const focusParentWindow = () => {
  (window as any).open('', ParentWindowName).focus();
};

答案 5 :(得分:-6)

如果这是您自己打开的窗口,则可以使用opener.focus();