I have a situation where, when a user pushes a button I perform an ajax request, and then use the result of the ajax request to generate a URL which I want to open in a new tab. However, in chrome when I call window.open in the success handler for the ajax request, it opens in a new window like a popup (and is blocked by popup-blockers). My guess is that since the the success code is asynchronous from the click handling code that chrome thinks it wasn't triggered by a click, even though it is causally related to a click. Is there any way to prevent this without making the ajax request synchronous?
EDIT
Here is some minimal code that demonstrates this behaviour:
$('#myButton').click(function() {
$.ajax({
type: 'POST',
url: '/echo/json/',
data: {'json': JSON.stringify({
url:'http://google.com'})},
success: function(data) {
window.open(data.url,'_blank');
}
});
});
http://jsfiddle.net/ESMUA/2/
One note of clarification: I am more conerned about it opening in a separate window rather than a tab, than I am about it being blocked by a popup blocker.
Try to add
window.open(url,'_blank');
Edit
Well, I don't think you can get around popup-blockers when opening a page that's not the immediate result of a user action (i.e. not async).
You could try something like this though, it should look like a user action to a popup-blocker:
var $a = $('<a>', {
href: url,
target: '_blank'
});
$(document.body).append($a);
$a.click();
Edit 2
Looks like you're better of keeping things sync.
As long as the new window is "same origin" you have some power to manipulate it with JS.
$('#a').on('click', function(e){
e.preventDefault();
var wi = window.open('about:blank', '_blank');
setTimeout(function(){ // async
wi.location.href = 'http://google.com';
}, 500);
});
Try adding async: false. It should be working
$('#myButton').click(function() {
$.ajax({
type: 'POST',
async: false,
url: '/echo/json/',
data: {'json': JSON.stringify({
url:'http://google.com'})},
success: function(data) {
window.open(data.url,'_blank');
}
});
});
What worked for me was:
var win = window.open('about:blank', '_blank');
myrepository.postmethod('myserviceurl', myArgs)
.then(function(result) {
win.location.href = 'http://yourtargetlocation.com/dir/page';
});
You open the new window tab before the sync call while you're still in scope, grab the window handle, and then re-navigate once you receive the ajax results in the promise.
The answer posted by #pstenstrm above (Edit 2) mostly works, but I added just one line to it to make the solution more elegant. The ajax call in my case was taking more than a second and the user facing a blank page posed a problem. The good thing is that there is a way to put HTML content in the new window that we've just created.
e.g:
$('#a').on('click', function(e){
e.preventDefault();
var wi = window.open('about:blank', '_blank');
$(wi.document.body).html("<p>Please wait while you are being redirected...</p>");
setTimeout(function(){ // async
wi.location.href = 'http://google.com';
}, 500);
});
This fills the new tab with the text "Please wait while you are being redirected..." which seems more elegant than the user looking at a blank page for a second. I wanted to post this as the comment but don't have enough reputation.
There is no reliable way. If your tab/window has been blocked by a pop-blocker in FF and IE6 SP2 then window.open will return the value null.
https://developer.mozilla.org/en-US/docs/Web/API/Window/open#FAQ
How can I tell when my window was blocked by a popup blocker? With the
built-in popup blockers of Mozilla/Firefox and Internet Explorer 6
SP2, you have to check the return value of window.open(): it will be
null if the window wasn't allowed to open. However, for most other
popup blockers, there is no reliable way.
Related
I've searched on the internet for a while for my solution, but none of the solutions worked for me or I didn't used it correct (I think).
I have a function which looks like this and is being called when a image is clicked:
function goToGoogle() {
setTimeout(function() {
$.ajax("url/path", {
data: "data"
}, function(data){
window.open("https://www.google.nl", "_blank");
});
}, 10000);
}
When window.open is called, a message pops up and says that the popup is blocked.
I've tried to create a variable with window.open in it (var myWindow = window.open( ... );) and then set the correct url with myWindow.location = "www.correct.url";. But this will result in a error in the console.log, which says that myWindow is undefined and location can't be called because of that.
Another thing I tried was to set async to false in the ajax call, but that's depreciated.
Does anyone how to make sure it opens a new window, even a few seconds after the click event?
By the way, I need the timeout of 10 seconds.. Nothing more, nothing less.
Your code works perfectly, because
a message pops up and says that the popup is blocked.
That's just a browser policy to block popups. That's up to user to allow open popups on your site or to forbid.
From time to time, I face a very intriguing bug. My javascript code does not display an alert(msg) during execution, but if I use a console.log(msg) it does show up in the console. What could prevent alert() from displaying?
Thanks a lot
This is a very common problem, and everyone has faced this problem atleast once.
The reason alert() does not work is because previously you have checked "prevent this page from creating additional dialoug" checkbox.
lets take a look at this code.
<script type="text/javascript">
var js_name = ['elem1', 'elem2']
for (var i = 0; i < js_name.length; i++) {
alert(js_name[i]);
};
</script>
There will be two alert boxes if you run the code. If you check the "prevent this page from creating additional dialoug" checkbox and then refresh the page again you won't get alert box ever again.
Solution is you need to close that webpage and reopen again in the browser(don't need to close the entire browser).
I am assuming you are using chrome.
Internet Explorer or FireFox doesn't have this checkbox feature.
If you override alert function so it won't work
alert = function()
{
...
};
alert('hello') // won't show any alert
To my knowledge alert() is always shown unless it is repetitive in which case you are asked if you want to continue showing alerts.
I suppose the specifics on how this is handled depends on your browser. Care to share any more details? :)
This also happens in ColdFusion. If you use anywhere after the script tag a cflocation tag (instead of location.href) the alert will not show.
This can also happen in Firefox if you have Dev Tools open and Responsive Design Mode enabled. It sounds like it's a bug.
In Firefox: go to Options -> Content and uncheck "block pop-up windows" check box. Restart browser.
Another reason why alert, confirm, and prompt may be ignored by the browser, is if the document is in an iframe that has a sandbox-attribute without allow-modals in its value.
For example, Firefox silently ignores this, however Chromium shows a warning.
If you try to execute javascript alert function in a Chrome browser address URL, you will not get the message if the the tab has no page previously loaded.
You will get the alert box only if it is not a fresh tab.
If there exists a web page that is previously loaded, and then you try to run the javascript in the address bar, you will get the expected result.
Hope it clarifies this difficult to detect behavior in Chrome.
If you have a location.reload() after the alert() function as shown below, JavaScript somehow skips the alert and reloads the page.
$.ajax({
url:'xxx',
type : 'POST',
data : datavalues,
dataType: 'json',
contentType: 'application/json',
success: function(response){
if(response.status == '200')
{
alert("updated");
}
}
});
location.reload();
To tackle this situation, I moved the reload function into the if block and this solved the issue.
$.ajax({
url:'xxx',
type : 'POST',
data : datavalues,
dataType: 'json',
contentType: 'application/json',
success: function(response){
if(response.status == '200')
{
alert("updated");
location.reload();
}
}
});
I have a similar problem here, when I replace the console log with "alert" it is not working but console.log does work.
The not working code is :
request(options, function(error, response, body) { // Requesting API
var statusCode = response.statusCode;
if(statusCode === 200){
alert("Success");
} else {
alert(error);
}
and the working code is:
request(options, function(error, response, body) { // Requesting API
var statusCode = response.statusCode;
if(statusCode === 200){
console.log("Success");
} else {
console.log(error);
}
This is something that's been driving me nuts.
I'm trying to detect whether the uses closes or navigates away from a page in order to do an ajax response upon the event. I have tried almost every possible method to invoke this but no luck. The only thing I can think of is that the activate window in question was fired using: window.open() method. Could that cause any issues? What I have so far:
window.onbeforeunload = function() {
//ajax stuff here
};
However, I've noticed that this does not work after the page is fully loaded. The event fires within the first few milliseconds (if I open the window and try to close it right away) during the page load and won't work after that.
Any ideas?
I once ran into this issue, and found it worked for me only by setting async : false on the ajax, like this:
jQuery(window).bind('beforeunload', function () {
jQuery.ajax({
url: 'your.url',
async: false,
data: yourdata
timeout: 2000 // or whatever timeout in milliseconds you want
success: function(data){
// Do whatever you want
}
});
});
As Ian mentioned on the comments, it's a good idea to set a timeout to prevent the window for taking too long to close in case the request takes a while. And keep in mind it won't work in all browsers...
This also supports old versions of IE and Firefox.
window.onbeforeunload = function (e) {
var message = "Your confirmation message goes here.",
e = e || window.event;
// For IE and Firefox
if (e) {
e.returnValue = message;
}
// For Safari
return message;
};
Ok. I'm trying to login to twitter. The window is not opening in this code. The response that gets alerted is not null and is a link to a login screen. Any ideas?
var url = "./twitter_login.php";
var con = createPHPRequest();
con.open("POST",url,true);
con.setRequestHeader("Content-type","application/x-www-form-urlencoded");
con.send("");
var response = "";
con.onreadystatechange = function() {
if(con.readyState==4 && con.status==200) {
response = con.responseText;
alert(response);
window.open(response,"twitter","menubar=1,resizable=1,width=350,height=500");
}
}
The standard popup-blocker logic contained in most browsers these days will block any calls to window.open() that are not the direct result of a user action. Code that is triggered by timers or by any asynchronous callback (like your ajax ready function) will be treated as NOT caused directly by user actions and the new popup window will generally be blocked.
You can verify this is what is happening by temporarily changing your browser's popup blocking (turning it off) and see that it then starts working.
Probably what you need to do as a work-around is to create the window upon the user action that started this thread of code and then put the content into the window when you get your ajax response. The browser will probably allow that. I know that's less desirable from a visual perspective, but you can put some temporary content in the window until the ajax response comes in (something like "loading...").
Just had this exact same issue. Just in case you wanted the code that fixed it. I used this:
newWindow = window.open("", "_blank");
request = $.ajax({ ... my request which returns a url to load ... })
request.done((function(_this) {
return function(data, textStatus, jqXHR) {
return newWindow.location = data.Url;
};
})(this));
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 that was just saved.
But as-is, the window.open function gets blocked by popup blockers.
Here's the basic parts of my code:
HTML:
Preview
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
}
}