How to avoid javascript `window.open` triggering popup window alert - javascript

I'm trying to build an off-site notification function in jQuery. The script first checks if the link is an external link and then checks against a db table entries for exceptions. If the link is external and not on the list of exceptions, send the visitor to a notification page. If it is an external link that's on the exception list, then open the link in a new window without the notification page.
I'm using a jQuery $.post call to send the link info out to a php script that retrieves the exceptions and returns a yes or no for if it needs to go to the notification screen. Here's the code:
$('a').click(function(){
var url =$(this).attr('href');
if(url !== '#'){
// ignore links that don't 'go' anywhere
if($(this).hasClass('alerted')){
// .alerted is used on the notification page to show the user's already been notified & prevents an infinite loop of notifications.
window.open(url);
return false;
}else if(url.substr(0,4) !='http'){
// check that the url isn't an internal link ('/page.php' for example)
return true;
}
// ajax script to check url is external and is there an exception. Returns as json object:
// link: link
// notify: true/false
$.post("/scripts/form_process.php", { action : 'offsite', link: url}, function(data){
if(data.notify == true){
// if visitors should be notified, redirect to the following link:
window.location= '/leaving-site?link='+encodeURIComponent(data.link);
return false;
}else{
// if the link is in the exception list, don't notify but do open the link in a new window:
window.open(data.link);
}
});
return false;
}
});
This is working fine except that so long as the window.open(url) command is inside the $.post success function, the browser is treating it like a popup instead of as a natural link. This seems to be a problem when using window.open inside the ajax call as far as I can tell. When I use it here:
if($(this).hasClass('alerted')){
// .alerted is used on the notification page to show the user's already been notified & prevents an infinite loop of notifications.
window.open(url);
return false;
}
I don't get the pop up blocker.
I can't hard code the exceptions list and I have to check every link - I can't assume a class will be added to the links that need to be notified for example.
How can I open the external link in a new tab and avoid the popup blocker in this code?

The classic way to solve this is as follows:
Create the new window before the AJAX call:
var newWindow = window.open('', '_blank');
And in the success - you assign the URL to the new window like so:
newWindow.location.href = 'http://example.com';
Full example with your code:
$('a').click(function(){
var url =$(this).attr('href');
if(url !== '#'){
// ignore links that don't 'go' anywhere
if($(this).hasClass('alerted')){
// .alerted is used on the notification page to show the user's already been notified & prevents an infinite loop of notifications.
window.location = url;
return false;
}else if(url.substr(0,4) !='http'){
// check that the url isn't an internal link ('/page.php' for example)
return true;
}
// ajax script to check url is external and is there an exception. Returns as json object:
// link: link
// notify: true/false
var newWindow = window.open('', '_blank');
$.post("/scripts/form_process.php", { action : 'offsite', link: url}, function(data){
if(data.notify == true){
// if visitors should be notified, redirect to the following link:
newWindow.location.href= '/leaving-site?link='+encodeURIComponent(data.link);
return false;
}else{
// if the link is in the exception list, don't notify but do open the link in a new window:
newWindow.location.href(data.link);
}
});
return false;
}
});

Related

Determine if the browser already opened an URL

We use an internal system (with FF as default browser)
We need to avoid that the user open the same URL in different tabs.
As the tabs share the same PHP session we get a mess.
So actually I'm looking to the way to check programmatically if certain URL is already opened in one of the opened tabs.
Client side (JS) or server side (PHP).
We use now the FF extension "Duplicate Tabs Closer" that helps.
But I'd prefer to keep full control (give warning, choose for which URL it works).
You can write cookie after your page loaded in the first tab, check it on the server side and show the user warning instead of actual page content if this cookie is set and the second tab is opened. To handle the case when a user closes the only opened tab you can remove that cookie in onbeforeunload handler.
Working off of Oleksandr's answer, you can store a map of number of times a url is opened, in a cookie. When a page is opened, increment the number or set it to 0. When a page is closed, decrement it or delete it.
function incrementTabsOpen() {
let tabsOpen = readObjCookie('tabsOpen') || {};
if (tabsOpen[window.location.href]) tabsOpen[window.location.href]++;
else tabsOpen[window.location.href] = 0;
writeObjCookie('tabsOpen', tabsOpen);
}
function decrementTabsOpen() {
let tabsOpen = readObjCookie('tabsOpen') || {};
if (tabsOpen[window.location.href]) tabsOpen[window.location.href]--;
if (tabsOpen[window.location.href] === 0) delete tabsOpen[window.location.href];
writeObjCookie('tabsOpen', tabsOpen);
}
// https://stackoverflow.com/a/11344672/3783155
function readObjCookie(name) {
let result = document.cookie.match(new RegExp(name + '=([^;]+)'));
if (result) result = JSON.parse(result[1]);
return result;
}
function writeObjCookie(name, value) {
document.cookie = name + '=' + JSON.stringify(value);
}
and
window.addEventListener('load', function() {
incrementTabsOpen();
};
window.addEventListener('unload', function() {
decrementTabsOpen();
};

Opening up new tab based on ajax response - Angular JS

On clicking a hyperlink,
{{id}}
I require something to open up in a new tab based upon the response (a flag, lets say - responseFlag) that I get from the ajax call.
Two methods I tried.
Note : Function is dependent on the id, so not using it on page load.
1.
$http.get(url).success(function(response) {
if(response.data.responseFlag==true){
$window.open("http://www.example.com");
}
else{
//perform something else other that window.open
}
});
The problem here is the 'Popup blockers' in the browsers (Chrome, Mozilla) - that keeps blocking them.
2.
var w = $window.open("","_blank");
$http.get(url).success(function(response) {
if(response.data.responseFlag == true){
w.location = "http://www.example.com";
}
else{
//perform something else
}
});
Here, if the 'responseFlag = true', it opens up in new tab. But as you might have guessed it, for 'responseFlag = false' too the tab opens up. I can use w.close() in the 'else' perhaps. But I think that's not a solution.
Help me out friends !
In your second example you're openning the new tab before doing the request, so it doesn't matter wich callback gets executed, you'll get a new window openned.
I don't see any reason why $window.open(...) works with your second example but not in the first, maybe is because the "_blank" parameter...
So, can you try this way?
$http.get(url).success(function(response) {
if(response.data.responseFlag == true){
var w = $window.open("","_blank");
w.location = "http://www.example.com";
}
else{
//perform something else
}
});

javascript check which URL loaded and give notification

I'm trying to find a way in javascript to check which URL is loaded, then have a popup notifying the user to update their old bookmarket and have it redirect to the new location in a few seconds.
For example, the url maybe Http:\abc\myappage and I want to check if they are on the http:\abc site which if they are, the notification pops up and redirects them.
Currently I have a simple redirect to take them to the new site, but I never considered anyone that has an old bookmark which would never get updated if you don't inform them about the change.
Thanks.
You can access the current url from within JavaScript with window.location.
Using window.location you can access the current domain and path, then by setting window.location.href = 'your new site' after a few seconds or after some user interaction will cause the browser to navigate to the supplied url.
if(window.location.host === 'abc'){
alert('This url is no longer valid.');
window.location.href = 'http://abc/myappage
}
You can use window.location to get some information regarding the current url:
window.location.origin in the console on this current page, prints:
"http://stackoverflow.com"
Then you could run some JS logic to check against your other url and use alert() to crete the pop up.
working JSBIN: https://jsbin.com/gijola/edit?js,console
adding code:
function checker (url) {
var here = window.location.origin;
l(here);
if (here !== 'whatever you want to check') {
alert('please update your bookmark!!');
}
}

On Internet Explorer, window.opener is lost after submitting form to a different URL and then coming back

There is a popup window that submits its form to a third party url on load.
The user selects his address using the third party service.
When the user clicks on the finish button of the third party service, the third party service redirects the user back to my original popup url.
The source code of the popup.jsp looks like this.
<%
String inputYn = request.getParameter("inputYn");
String roadFullAddr = request.getParameter("roadFullAddr");
String roadAddrPart1 = request.getParameter("roadAddrPart1");
String roadAddrPart2 = request.getParameter("roadAddrPart2");
String engAddr = request.getParameter("engAddr");
String jibunAddr = request.getParameter("jibunAddr");
String zipNo = request.getParameter("zipNo");
String addrDetail = request.getParameter("addrDetail");
String admCd = request.getParameter("admCd");
String rnMgtSn = request.getParameter("rnMgtSn");
String bdMgtSn = request.getParameter("bdMgtSn");
%>
function init(){
var url = location.href;
var confmKey = "serviceKeyIssuedBytheThirdParty";
var inputYn= "<%=inputYn%>";
if(inputYn != "Y"){
document.form.confmKey.value = confmKey;
document.form.returnUrl.value = url;
document.form.action="http://www.somethirdpartyservice.do";
document.form.submit();
}else{
try {
opener.jusoCallBack("<%=roadFullAddr%>","<%=roadAddrPart1%>","<%=addrDetail%>","<%=roadAddrPart2%>","<%=engAddr%>","<%=jibunAddr%>","<%=zipNo%>", "<%=admCd%>", "<%=rnMgtSn%>", "<%=bdMgtSn%>");
} catch (err) {
alert(err.description || err) //or console.log or however you debug
}
window.close();
}
}
The javascript jusoCallBack function on the parent page.
function jusoCallBack(roadFullAddr,roadAddrPart1,addrDetail,roadAddrPart2,engAddr, jibunAddr, zipNo, admCd, rnMgtSn, bdMgtSn){
console.log("jusoCallBack");
document.form.newAddress.value += roadFullAddr;
}
The problem is that it works just fine on Google Chrome but I get an error that says Unable to get property 'jusoCallBack' of undefiend or null reference.
I experimented so that the function jusoCallBack will be fired on the first popup window load, before it submits the form to the third party URL.
The popup window finds its opener just fine and the function jusoCallBack is fired.
It seems to me that, for some reason, the popup window loses the opener information after it had navigated to a third party URL.
But it works just fine on Google Chrome though. So I'm not so sure.
Is the popup window supposed to remember who the opener is even after the popup windows had navigated out to a different URL or is it normal for the popup window to lose its opener?

what is return type of window.open() in Javascript

I am writing code to download a PDF file using window.open(). I am passing the URL path of the pdf file on a server.
window.open(url, name, "width=910,height=750,scrollbars=yes");
I want to check if the downloading of file is successful or not. What is the return type of window.open()?
I tried like this
try
{
window.open(url, name, "width=910,height=750,scrollbars=yes");
alert("success");
}
catch(e)
{
alert("failer");
}
When I change the URL to a wrong URL, it shows the same result as a success.
http://www.javascripter.net/faq/openinga.htm
The return value is the reference to your new window. You can use
this reference later, for example, to close this window
(winRef.close()), give focus to the window (winRef.focus()) or perform
other window manipulations.
Window.open either returns a handle to the new window opened or null, it will not tell you if the page within the window loaded successfully. If you where opening an html page (from the same domain) you could use this to look into the document
var newWin = window.open();
if(newWin == null) {
alert("darn");
}
newWin.document.getElementById("anElement").innerText = "Fish";

Categories