Window 焦点在 Javascript 中不起作用

Window focus is not working in Javascript

当我单击“笔记本”按钮时,我希望它打开 notebook.html,如果我再次单击它,我希望 Notebook.html 进入焦点而不刷新。 (用户更新Notebook.html,刷新会丢失他们更新的数据。)

这部分有效,但它确实刷新了页面,我丢失了所有已添加的数据。

<script>
function openNotebook() {
    window.open('notebook.html', "notebook","width=800, height=600, resizable=yes, top=50, left=10").focus();
}
</script>

<button type="button" class="btn btn-primary" onclick="return openNotebook()">Notebook</button>

试试这个

  • 测试你是否已经打开它
  • return false 停止可能的表单提交或使用 type="button"
  • 删除参数中的空格

var w;
function openNotebook() {
  if (w && !w.closed) w.focus(); // focus if exists and is not closed
  else w = window.open("notebook.html","notebook",
    "width=800,height=600,resizable,top=50,left=10");

  return false; // or preventDefault or make the button type="button"
}

测试是否 w.closed 的替代方法,通过在 notebook.html

中添加这个来从开场白中删除 w
window.onbeforeunload=function() { opener.w=null; }