dead pimp
dead pimp

Reputation: 23

Refresh currently open tab with Javascript when a new tab is opened

Would it be possible to refresh the currently open tab when a new tab is opened by clicking a link in the first tab? Basically, the end result would be like this: the first tab is open, a link on the page which is open in the first tab is clicked (with middle mouse button or something similar to that, just to make it open in the second tab), link which was clicked is opened in the second tab and then the first tab is automatically refreshed. I hope that I explained it understandably. Note: I'm not designing my own website, I'm looking to make a plugin for the website with Greasemonkey.

Upvotes: 2

Views: 18700

Answers (3)

Fefux
Fefux

Reputation: 974

You need something like this (jquery code inside) :

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Title</title>
  <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
</head>
<body>
    <a id="myLink" href="http://www.google.com">Click me</a>
    <div id="toUpdate">Not updated</div>
</body>

<script>
$(function() {
    $("#myLink").on("click", function(event) {
        event.preventDefault();
        window.open(event.target.href, '_blank');
        $("#toUpdate").text("Go on google");
    }).on("mousedown", function(event) {
        event.preventDefault();
        if (event.which === 2)
            $("#toUpdate").text("Go on google");
    });
});
</script>
</html>

Edited to add Firefox support

Upvotes: 0

besciualex
besciualex

Reputation: 1892

Let's assume you have this link on your page:

<a href="http://server.com/url-to-second-tab" target="_new">Link which opens new tab and refreshes current one</a>

In js script you add this (assuming you are using jQuery, as you stated):

$(document).ready(function(){
   $('body').on('click','a',function(e){
        e.preventDefault()
        // Open new tab - in old browsers, it opens a popup window
        window.open($(this).attr('href'), '_blank');
        // reload current page
        location.reload();
   })
})

Please test it in all browsers, as in some browsers it may open the link as a popup window instead of a new tab.

As a fast test, open with F12 developer tools on Chrome, and write in console:

window.open('https://google.com', '_blank');location.reload();

Upvotes: 2

P. Frank
P. Frank

Reputation: 5745

Yes it is with document.body method.

Declare your window:

w = window.open("yourUrl", "MYtest", "width=700, height=500");

And in your function you can access with document.body method:

html = "I Append my new html";
$(w.document.body).html(html);

Upvotes: 0

Related Questions