首页 > 解决方案 > 如果更改 url 失败,如何让 Chrome 抛出异常

问题描述

我有一个用 js 打开的新窗口的参考

var theNewTab="";
theNewTab = window.open(theURL, 'winRef');

然后我在用户单击父窗口中的另一个链接时使用

theNewTab.location.href = targetLink;
theNewTab.focus();

如果窗口不再存在“关闭”取消链接 FF 和 IE,我使用 chrome 的 id 不会引发异常,我用它来再次打开窗口。

try {
   theNewTab.location.href = targetLink;
   theNewTab.focus();
}catch(err) {
   theNewTab = window.open(theURL, 'winRef');
   theNewTab.focus();
}

PS:我每次都尝试使用“window.open”,但如果窗口已经打开,id 不会重新加载页面,或者它不会重新执行我认为文档中准备好的脚本。

标签: javascriptgoogle-chromeexception

解决方案


我不确定你需要什么。

<script type="text/javascript">
  var theNewTab = null;

  function openNewTab(theURL) {
    if (theNewTab == null || theNewTab.closed == true) {
      theNewTab = window.open(theURL);
    } else {
      theNewTab.location.href = theURL;
    }
    theNewTab.focus();
  };

  // use the function when you need it
  $('a').click(function() {
    openNewTab($(this).attr('href'));
  });
</script>

这个例子对你有帮助吗?


推荐阅读