I'm trying to open a jsp page in a new window. Using javascript window.open
yeild开发者_如何学Cs browser warnings and in some cases (firefox) will block the popup by default. Is there any way around this (this isn't a malicious application - its an internal user tool)?
Most browsers will not block a popup if it is triggered by user action, such as clicking a button. For example, if your window.open
javascript is attached to a button's onclick
event, browsers will not block it.
On the other hand, if you're trying to display a popup without any user action, you're out of luck. That's exactly the technique that annoying advertisements use, so browsers can't distinguish between your app from annoying ads.
I will share my solution here as I see none was provided.
First thing first
When a popup opens, every browser has an acceptable time limit after which it removes the “trust”, assuming that now it’s outside of the user action and blocks the popup. This time limit varies from browser to browser, for instance for chrome its 3 seconds while for firefox is 2 seconds.
How to stop browser from blocking popups
First of all, you need to make sure that you open a popup ONLY on some user action.
However, it's not possible always. For instance, I needed to open a popup to load a pdf of an invoice every time user clicked "print Invoice". I did not have pdf at the moment when user clicked the button, I needed to do the following:
- Make an ajax request
- generate a pdf on server
- send back a public accessible path which I would load into the popup to show pdf in browser
Now, above process always took variable time based upon how complicated pdf was and how fast was client's internet.
I ran into this very issue, and browser blocked my popup.
So a simple solution of it is:
- Open a popup right away when user clicks on a button
- Switch focus to that popup
- then make ajax request and get the loading path or whatever it is you need from server.
- load the url in the popup or modifications you need based on server response.
Here is some line of code to help you actually implement above mentioned points:
let newWindow = open('/', 'example', 'width=300,height=300')
newWindow.focus();
let data = {
//whatever data you need to provide
};
//send ajax
$.ajax({
type: "POST",
url: yourUrl,
headers: {
//if you use XCSRF or add any other header you might have
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: data,
success: function( response ) {
//load the returned content in new window
//or whatever else you need to do
newWindow.location.href = response.path;
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest, textStatus, errorThrown);
}
});
Of course, you will need to tweak it as per your need but I hope it will help you guide in right direction.
I have solved my issue based on useful information about popup provided here
I hope it helps
精彩评论