How can I get the recently opened browser tab name from the Start tab?

My code, like this one, is to create a new tab from one tab to another in the same browser.

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(); } 

It works correctly on the code to create a new tab. when you click on the link "MyNewTab" on the main page

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

Again I try to switch the homepage to a newly opened tab. This time you need to switch from the home page to a new tab without rebooting. But this newtab content is reloading.

How to get the name of the tab and get the focus of the newly opened tab by clicking the "MyNewTab" link?

+5
source share
2 answers

you need to set the current selected tab in the javascript cookie and always read this cookie when the page loads and set the tab

you can set a cookie inside the newTab () function:

 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(); } 

then on the page load event:

 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 
+2
source

If you understand correctly, you just need to use window.open() and window.focus() .

Explanation:. When the user clicks the button, you check to see if a new tab is open. If so, you just use window.focus() . If not, you will open it using window.open() .

Like this:

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

Note: This code does not work in the snippet (because of security), so you can see it at http://jsbin.com/tebecu

+1
source

Source: https://habr.com/ru/post/1239575/


All Articles