开发者

window.open popup getting blocked during click event

开发者 https://www.devze.com 2023-03-18 20:17 出处:网络
What I ultimately need to do is run an $.ajax() call and then after that is run, open a new window. A use clicks on a \"Preview\" button that saves their current form then opens a new window that sho

What I ultimately need to do is run an $.ajax() call and then after that is run, open a new window.

A use clicks on a "Preview" button that saves their current form then opens a new window that shows a preview of the item with the data t开发者_如何转开发hat was just saved.

But as-is, the window.open function gets blocked by popup blockers.

Here's the basic parts of my code:

HTML:

<a href="/surveys/185/preview" class="preview" target="_blank">Preview</a>

JavaScript:

$('.preview').live('click', function(event){
  save_survey($(this).attr('href'));
  event.preventDefault();
});

function save_survey(url) {
  $.ajax({
    type: "POST",
    url: form_url,
    dataType: 'json',
    data: form_data,
    success: function(data) {
      window.open(url, '_blank');
    }
  });
}


I ran into this problem recently and found this work-around:

1) call window.open just before calling $.ajax and save window reference:

var newWindow = window.open(...);

2) on callback set location property of the saved window reference:

newWindow.location = url;

Maybe it will help you too.


Popup blockers usually works blocking every popup shown not triggered by a direct user action, like clicking on a button or a link.

If you use a ajax request on your click event, the request is fired asyncronous from the click event, that's why by the time the ajax request has done its job and you get your event with the response from the request you have lost your chance to trigger a window.open withouth the popup blocker getting in the way, the original click event it's long dead by that time.


According this this post, it looks like you would have to open your window in direct response to the click (to avoid getting hit by the popup blockers) rather than waiting until the AJAX call completes to open the new window.


I solved my case by making the Ajax call synchronous. E.g. (with jQuery):

$("form").submit(function(e){
    e.preventDefault();
    $.ajax({
      async: false,
      url: ...,
      data: ...,
      success: function(results){
          if(results.valid){
              window.open(...);
          }
      }
    });
    return false;
  });


const newWin = window.open(`${BASE_URL}`, 'expampleName')
if (newWin) {
  newWin.onload = () => {
    const currentOpenWindow = newWin
    const href = newWin.location.href
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消