【问题标题】:How can i get the newly opened browser tab name from origin tab?如何从源选项卡获取新打开的浏览器选项卡名称?
【发布时间】:2016-04-05 09:35:21
【问题描述】:

我这样的代码可以在同一浏览器中创建从一个选项卡到另一个选项卡的新选项卡。

function newTab()
{
    var form1 = document.createElement("form");
    form1.id = "newTab1"
    form1.method = "GET";
    form1.action = "domainname";  //My site address
    form1.target = "framename";   //Browser tab name
    document.body.appendChild(form1);
    form1.submit();
}

以上代码可以正常创建新标签。当点击“MyNewTab”链接主页时

<a href="javascript:newTab()" style=" margin-left:15px;" id="newTab"> MyNewTab </a>

我再次尝试将主页切换到新打开的选项卡。这次需要从主页切换到新标签而不重新加载。但是这个新标签内容重新加载了。

如何获取标签名称并通过单击“MyNewTab”链接获得新打开的标签的焦点?

【问题讨论】:

  • without reload 重新加载主页?是否要在不刷新主页的情况下打开新标签页?
  • 每次点击链接重新加载新打开的标签。我不需要这个活动。我需要在第二次单击时将焦点放在已经打开的选项卡上。有可能吗?
  • 这很容易......看我的回答。

标签: javascript jquery html


【解决方案1】:

您需要在 javascript cookie 中设置当前选择的选项卡,并始终在页面加载时读取此 cookie 并设置选项卡

您可以在 newTab() 函数中设置 cookie:

function newTab()
{
    var form1 = document.createElement("form");
    form1.id = "newTab1"
    form1.method = "GET";
    form1.action = "domainname";  //My site address
    form1.target = "framename";   //Browser tab name

    $.cookie("currentTab", "framename");//set the selected tab name in cookie

    document.body.appendChild(form1);
    form1.submit();
}

然后,在页面加载事件中:

var tabName=$.cookie("currentTab")//get the current tab name from cookie.
if(tabName==null){
tabName="default tab name"//at first time the cookie will be null, 
//so you need to assign a default value if the cookie is null
}

//set this tab as selected

【讨论】:

  • 我将这些行添加到我的代码中“$.cookie 未定义错误”发生。
  • 我需要为这个问题设置java脚本cookie谢谢你的帮助
  • 但您只需要添加 jquery 引用即可使上述代码正常工作
【解决方案2】:

如果我理解正确,您只需要使用window.open()window.focus()

说明:当用户点击按钮时,您会检查新标签是否已经打开。如果是这样,您只需使用window.focus()。如果没有,请使用window.open() 打开它。

像这样:

var new_win;
document.querySelector('button').onclick = function(){
  if (new_win) {
    new_win.focus();
  }
  else {
    new_win = window.open('second_page_url');
  }
};
&lt;button&gt;Open tab&lt;/button&gt;

注意:此代码在 sn-p 中不起作用(因为安全性),因此您可以在 http://jsbin.com/tebecu 中看到它

【讨论】:

  • 非常感谢它在 chrome 浏览器中运行良好。但不适用于其他浏览器,如(Firefox)。有什么解决办法吗?
  • 由于Firefox 的安全原因,我担心这是不可能的。 stackoverflow.com/questions/22052388/…
猜你喜欢
  • 2018-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-11
  • 2011-07-28
  • 2022-12-09
相关资源
最近更新 更多