Search code examples
javascriptbrowsertabswindowonfocus

can i switch focus on windows or tabs based on user input using javascript or any other tech?


  1. I have a webpage that shows a list of results.

  2. I click on one of the result to view a product. It opens up a new window/tab.

  3. Now I have 2 windows/tabs from the same website, but 1 showing result page and the other a product page.

  4. Inside the product page, I have a link that says "Back To List"

  5. If I press on it, I can go back to the same list of results.

  6. So now I have two windows/tabs showing the same list of results.

The new behavior I am interested to know if it works is:

a) if I click on Back To List in the product page, can I switch focus to the original window/tab that shows the list of results, rather than what I have described in 5 & 6?

b) if answer to a is yes, can I do for multiple product windows? ie if I repeat step 2 multiple times?


Solution

  • You can do something similar this:

    var BackToList = function() {
        window.opener.focus(); // this sets the focus on the window that opened your product
        window.close();  // and this closes the product window
    };
    

    Then your link should call the BackToList function..

    If your link is a simple a tag AND it has an id, you go like this on your window load event:

    document.getElementById("the id goes here").onclick = BackToList;