Why does using target="_blank" cause Javascript to fail? - javascript

I have a bunch of links that use a target="_blank" attribute to open in a new window. I want to attach Google Analytics goal tracking to clicks of these links.
To do this, I tried attaching an onclick="pageTracker._trackPageview('/event/outgoing')" attribute to the links.
But I discovered that for links with a target="_blank" attribute, the Javascript onclick event gets skipped. So the goal is not recorded. In other words, this link successfully records the goal:
Click me
But this does not:
Click me
Does anyone know why this might be occurring? Assuming there isn't an easy solution, I assume I'll have to use Javascript to solve the problem. The following code successfully records a goal (but does not open the link):
function attach_goal_tracking() {
var links = document.getElementsByClassName("buyTicketsLink");
for(var i=0; i<links.length; i++) {
links[i].onclick = record_goal;
}
}
function record_goal(e) {
e.stop();
pageTracker._trackPageview('/event/outgoing');
}
But when I add to the record_goal function to open the link...
function record_goal(e) {
e.stop();
pageTracker._trackPageview('/event/outgoing');
var newWindow = window.open(this.getAttribute('href'), '_blank');
newWindow.focus();
}
...then it fails to track the goal.
Can anyone tell me why this might be, and what I should do to get around this problem? FYI I'm using Prototype for Javascript.

There might be an issue with popup blockers (I'm thinking Googlebar) stopping the window from opening, and (with the presence of onclick) preventing the onclick code from running. For example see this and this similar sounding issues other people are having.
Or it might simply be that the click handler code is throwing an error that then prevents the rest of the code from completing. See my comment to your question re how you are binding the events. e.stop() may be failing in IE.
Your hypothesis however is false. target="_blank" and onclick="..." do work together just fine.
Testcase in point: http://jsbin.com/anahe (add /edit to the url to edit the code). You may need to turn off your popup blocker(s):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Sandbox</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<script>var clickCount= 0;</script>
</head>
<body>
<a href="http://www.google.com" target="_blank" onclick="document.getElementById('dbg').innerHTML = ++clickCount">
open new
</a>
<div id="dbg"></div>
</body>
</html>
Clicking on the link opens a new window and updates the div with the number of times the linked has been clicked. Tested this in IE6, IE7, FF2, FF3.5, Chrome 2, Chrome 3, Opera 9.

It is possible, victor is right the e.stop() is uneccessary, I can confirm that the following code successfully opens a new tab, and asynchronously alerts on the old tab (consequently making it regain focus).
reload
<script>
var as = document.getElementsByTagName('a');
for (var i = 0; i < as.length; i++) {
var a = as[i];
a.onclick = function(e) {
setTimeout(function() {
alert('hi hi');
}, 1000);
}
}
</script>
The next best thing is to have a link tracking page and route all your external links through that page.

Related

Beforeunload event does not fire after page refresh Chrome

I have this simple code
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<!--<script src="angular.min.js"></script>-->
<script>
window.onload = function () {
window.addEventListener("unload", function () {
debugger;
});
window.addEventListener("beforeunload", function () {
debugger;
});
window.onbeforeunload = function () {
}
}
</script>
</head>
<body ng-app="app">
</body>
</html>
I want unload or beforeunload events be fired after I refresh the page. This is not happening in Chrome VersiĆ³n 67.0.3396.62. I have tried firefox and edge and it works well. It also works when i close the tab. The error ocurrs only when i refresh the page.
You've run into an issue that was already reported. It looks like a bug, but according to a Chrome dev (kozy) it is a feature:
Thanks for repro. It is actually feature. As soon as you pressed reload we ignore all breakpoints before page reloaded. It is useful all the time when you have a lot of breakpoints and need to reload page to restart debugging session.
Workaround: instead of pressing reload button you can navigate to the same url using omnibox then all breakpoint will work as expected.
I've added bold emphasis to point out the workaround proposed by kozy. I've tried it and found that it works.
Other than the issue with the debugger statement, the handlers are executed whether you are reloading or closing the tab. In both cases that follow, I get the stock prompt that Chrome provides when returning true:
window.addEventListener("beforeunload", function (ev) {
ev.returnValue = true; // `return true` won't work here.
});
This works too:
window.onbeforeunload = function () {
return true;
}
It used to be that you could use a return value with a message and the browser would show your custom message but browsers generally no longer support this.
Whether or not you want to set the handler for beforeunload inside a handler for load is entirely dependent on your goals. For instance, I have an application for editing documents that does not set the beforeunload handler until the application has started initializing, which is much later than the load event. The beforeunload handler is there to make sure the user does not leave the page with unsaved modifications.

Why does this throw an exception in IE 11

Why does the following code throw an 'Unspecified error' (on the appendChild line) in Internet Explorer 11 which I click the button?
<!DOCTYPE html>
<html>
<head>
<script>
function go() {
var popUp = window.open('about:blank');
popUp.document.body.appendChild(document.createElement('div'));
}
</script>
</head>
<body>
<button onclick="go()">Click Me</button>
</body>
</html>
You're using the document of the current page to create the div, try using the document from the popup window
popUp.document.body.appendChild(popUp.document.createElement('div'));
Popup blockers will typically only allow window.open if used during the processing of a user event (like a click). That might be causing the problem if you have popups blocked.
You need to call window.open from an event initiated by the user, e.g. clicking on a link, and that link needs to have target="_blank". Otherwise, Chrome and Firefox will block the popup.
Also, the error is triggered because popUp is not checked for null before attempting to append the div to it. If there's no popup, you can't append an element to it.
(I forgot this bit and Musa made me remember, so thanks) IE will block appending any element created in a different window context from the window context that the element is being appending to. So, instead of creating the DIV node using the current document, you need to create it using the popUp's context.
Summing it all up, this is how it would look the code.
<!DOCTYPE html>
<html>
<head>
<script>
function go()
{
var popUp = window.open('about:blank');
try
{
// Make sure you have a body document when creating the new window....
popUp.document.write("<html><head><title></title></head><body></body>");
popUp.document.body.appendChild(popUp.document.createElement('div'));
}
catch(e)
{
console.log(e);
}
}
</script>
</head>
<body>
<button onclick="go()">Click Me</button>
</body>
</html>

JavaScript to open two web pages using one link

I need JavaScript code or HTML to make two websites open in two new browser tabs when clicking on one link. I do not want them to open in new windows, or on the current page that the link is on.
It probably won't work because the browser might consider it a popup and block it.
If the user allows popups you can do:
window.open(url, '_blank');
Like:
<a id="mydoublelink" href="http://site1.com" target="_blank">foo</a>
document.getElementById("mydoublelink").onclick=function(){
window.open('http://site2.com', '_blank');
}
If you call window.open in the onclick event you should be fine. Built-in popup blockers allow those. The kind of popups that get blocked come from other events or from scheduled events like a setTimeout.
document.getElement("my_link").onclick = function () {
window.open(/*..*/); // works
}
document.getElement("my_link").onclick = function () {
setTimeout(function () {
window.open(/*..*/); // will probably get blocked
});
}
This means, for instance, that if you open a popup after an AJAX call it will very likely get blocked. A workaround in this case is to open the popup right away and fill in the content later. This is outside the scope of this question but I feel like this is information that everyone should know.
Something like this?
<!DOCTYPE html>
<html>
<head>
<script>
function open_win()
{
window.open("URL");
open_win_two();
}
function open_win_two()
{
window.open("URL");
}
</script>
</head>
<body>
<a onclick="open_win()">luyfl</a>
</body>
</html>
Yu can try the new target _newtab:
blabla
It works in Firefox, don't know if it's supported in other browsers.

Prompt User before browser close?

We have an administrative portal that our teachers constantly forget to download their latest PDF instructions before logging out and/or closing the browser window. I have looked around but can't find what I'm looking for.
I want to accomplish the following goals:
Goal 1
Before a user can close the browser window, they are prompted "Did you remember to download your form?" with two options, yes/no. If yes, close, if no, return to page.
Goal 2
Before a user can click the 'logout' button, they are prompted with the same as above.
My first pass at the very basic code (which does not work for browser close) is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function init() {
if (window.addEventListener) {
window.addEventListener("beforeunload", unloadMess, false);
} else if (window.onbeforeunload) {
window.onbeforeunload = unloadMess;
};
}
function unloadMess() {
var User_Message = "[Your user message here]"
return User_Message;
}
</script>
</head>
<body onload="init();">
hello this is my site
</body>
</html>
EDIT - NEW ISSUES
The solution provided below works but also has its own issues:
When user clicks the link to actually download the forms, the page thinks they are trying to leave and in turn present an error message to them! Also - I would like for one event or another to occur but not necessarily both. I.e. they hit 'logout' button and they are presented with the OnClick event, THEN the browser prompt. Any ideas?
Update 2017
All modern browsers do not support custom messages any longer.
window.onbeforeunload = function(evt) {
return true;
}
This one for closing the tab:
window.onbeforeunload = function(evt) {
var message = 'Did you remember to download your form?';
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return message;
}
and use onClick event for logout button:
onClick="return confirm('Did you remember to download your form?');"
I think that this may be part of your problem:
else if(window.onbeforeunload) {
window.onbeforeunload = unloadMess;
};
That test in the "if" statement will only be true if there's already a handler function. That test doesn't mean, "does the window object have an 'onbeforeunload' property?". It means, "is the 'onbeforeunload' property of the window currently not null?".
I think it'd be safe to just set "onbeforeunload" directly, for any browser.
You cannot alert or things like that in onbeforeunload, you cannot simply return false to make the user not leave the page, as with other events like onclick. This would allow a site to make it impossible to leave it.
You can however just return a string, the browser then shows a confirm dialog including your string asking the user whether they really want to leave.
Pointy is right about browser close events - imagine if evil sites could prevent you from closing their windows?? So you cannot prevent them from closing your site, but you can do an alert.
As far as your logout button is concerned, that is much more straight-forward:
Logout

Weird behavior when trying to reuse a popup window

We have a client requirement that has stumped me, embarrassingly enough.
The client has a set of links that need to open in a popup window - if you click on any of the links, it should reuse the same popup window. Easy enough, I thought, so I threw something like this together:
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
var popupWin = null;
function openWindow(url) {
if (popupWin == null) {
popupWin = window.open(url,'p2p','');
} else {
if (!popupWin.closed) {
popupWin.location.href = url;
} else {
popupWin = window.open(url,'p2p','');
}
}
popupWin.focus();
}
</script>
</head>
<body marginheight="0" marginwidth="0" leftmargin="0" topmargin="0" bgcolor="#ffffff">
<ul>
<li>Google</li>
<li>FB</li>
<li>Apple</li>
<li>ESPN</li>
</ul>
</body>
</html>
If you put that into an html file, all behaves as expected.
My problem is that when I use the client's intranet URLs per their requirement, the behavior I see is as follows:
Click on one of the popup links (popup link opens in a new window)
Click on another of the popup links (link replaces page opened in the first popup)
Close the popup window.
Click one of the popup links (doesn't matter which, opens in a new popup window as
expected)
Click on another of the popup links (popup opens in a new popup window, not reusing the popup window as expected)
The weird thing is that if I step through the javascript code in Firebug, it correctly gets to the branch of the if statement that determines that the popup window exists and is not closed (so it should be reused), but the line of code:
popupWin.location.href = url;
Ends up opening a new window for some reason.
So, any idea what's going on? I'm guessing something bizarre on the pages that the client wants me to popup is screwing things up in some mysterious fashion, but I can't figure out what it is. Wish I could provide the links to you, but unfortunately they're private.
Thanks much for any help.
Mustafa
Isn't this functionality inherent in HTML? Shouldn't it work without the javascript?

Categories