Skip to content
Advertisement

How to use window.open to open in same tab (using self does not work)

I have some custom long JS code that is too long to post, basically when user clicks a button on my site, it is creating a custom <form>, and submits it as POST request in a new tab that gets opened.

I want to modify it to open in the same tab. The relevant line of code is:

w = window.open("",'myPop_Window' + wId);

And I’ve tried changing it to:

w = window.open("",'myPopup_Window' + wId, "_self");

But it didn’t work.

I hope this is enough info to figure how can I modify the line to open in same tab.

EDIT:

more code of form creation:

var tryOpenTab2 = function(button,tab_url,tab_url_data_g) {
    var data = {};
    var form = button.parents('form').first();
    if (form.length > 0)
        data = getFormData(form);
    if (tab_url_data_g) {
        data['g'] = tab_url_data_g
    }

    if (!tab_url)
        return;

    var form = $('<form></form>');
    
    form.attr('method', 'POST');
    
    form.attr('action', tab_url);
    for (var k in data) {
        var input = $('<input />');
        input.attr('type', 'hidden');
        input.attr('name', k);
        input.attr('value', data[k]);
        form.append(input);
    }
    $('body').append(form);

    if (w && !w.closed) {
        //w.close();// client want to always open new tab
        w = null;
    }
 
        wId = ''+new Date().getTime();
        
 
        w = window.open("",'myPopup_Window' + wId); 
 
    
        form.attr('target', 'myPopup_Window' + wId);
 
    }

EDIT 2:

How shoudl I used wId in new code?

if (button.is(button_class3)) {
    w = window.open(window.location.href.split('#')[0] + "#" + button.attr("data-popup-id"));
} else {
    wId = ''+new Date().getTime();
    
  if(  (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent))) {  
    
    // w = window.open("",'myPopup_Window' + wId);   old line
    
    w = window.open("","_self") // new line 1
    form.attr('target', '_self'); // new line 2
    
}
else { // non mobile agent - use blank
    w = window.open('about:blank','myPopup_Window' + wId);
    
    form.attr('target', 'myPopup_Window' + wId);

}

Advertisement

Answer

I suspect you can remove tryOpenTab2 from the submitting process and just have the form submit as normal without a target

Else try this

Change

if (w && !w.closed) {
  //w.close();// client want to always open new tab
    w = null;
}
wId = ''+new Date().getTime();
w = window.open("",'myPopup_Window' + wId); 
form.attr('target', 'myPopup_Window' + wId);

to

 form.attr('target', '_self');
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement