Amran Amran - 4 months ago 34
jQuery Question

jQuery - Prevent Pop Up Blocker Using Window.Open();

How can I avoid browser from Pop Up Blocker if I use jQuery to open in a new window. I been googling regarding this issue but still stuck with it. This is the codes that I made,

$(document).ready(function(){
$('#newLink').click(function(event){
event.preventDefault();
var page = $(this).attr('href');
$.post(page,
{
pr_no : pr_no
})
.done(function(data){
window.open(page, "MsgWindow", "width=800,height=800");
});
});

Answer

Popup blockers will typically only allow window.open if used during the processing of a user event (like a click). In your case, you're calling window.open later, not during the event, because $.getJSON is asynchronous.

You have two options:

Do something else, rather than window.open. Make the ajax call synchronous, which is something you should normally avoid like the plague as it locks up the UI of the browser. $.getJSON is equivalent to:

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

...and so you can make your $.getJSON call synchronous by mapping your params to the above and adding async: false:

$.ajax({
    url:      "redirect/" + pageId,
    async:    false,
    dataType: "json",
    data:     {},
    success:  function(status) {
        if (status == null) {
            alert("Error in verifying the status.");
        } else if(!status) {
            $("#agreement").dialog("open");
        } else {
            window.open(redirectionURL);
        }
    }
});

Again, I don't advocate synchronous ajax calls if you can find any other way to achieve your goal. But if you can't, there you go.

Here's an example of code that fails the test because of the asynchronous call:

Live example | Live source (The live links no longer work because of changes to JSBin)

jQuery(function($) {
  // This version doesn't work, because the window.open is
  // not during the event processing
  $("#theButton").click(function(e) {
    e.preventDefault();
    $.getJSON("http://jsbin.com/uriyip", function() {
      window.open("http://jsbin.com/ubiqev");
    });
  });
});

And here's an example that does work, using a synchronous call:

Live example | Live source (The live links no longer work because of changes to JSBin)

jQuery(function($) {
  // This version does work, because the window.open is
  // during the event processing. But it uses a synchronous
  // ajax call, locking up the browser UI while the call is
  // in progress.
  $("#theButton").click(function(e) {
    e.preventDefault();
    $.ajax({
      url:      "http://jsbin.com/uriyip",
      async:    false,
      dataType: "json",
      success:  function() {
        window.open("http://jsbin.com/ubiqev");
      }
    });
  });
});