[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Getting new url href from current page using javascript

Posted on 2007-10-12
31
Medium Priority
?
1,025 Views
Last Modified: 2013-11-19
Using javascript and HTML (some flash too). I want to be able to read where the user is going before the user leaves my page. I have flash content which has links as well as static HTML anchor tags and DHTML onclick and onchange events.  I do _not_ have access to change all of the code to use a single wrapper function for redirection.

I am trying to get the new url (href of an anchor tag, location of onclick, etc), using javascript, before my page unloads.

Basically I want a document.nextLocation or document.location.newHref. But such doesn't exist.

I have looked through the JavaScript reference from Mozilla and read through ECMA-262 and W3C DOM Level 1. No luck.  I have Googled most of the morning using searches like "javascript new url" "capture href javascript" "read new url page unload" and many, many more. Still no luck.

Any ideas?
0
Comment
Question by:karlwilbur
  • 13
  • 8
  • 5
  • +3
30 Comments
 
LVL 29

Expert Comment

by:Badotz
ID: 20069215
Create a handler for the window.unload event and check the event object for the <a> tag.

IE:
win_unload(e)
{
    // do whatever here...
}
0
 
LVL 29

Expert Comment

by:Badotz
ID: 20069222
Granted, this is only pseudocode, but if you search Google for 'window.unload', you should find something to help you.
0
 
LVL 6

Author Comment

by:karlwilbur
ID: 20069290
I have tried using onUnload as a breakpoint to search the DOM for the requested URL, but I cannot find it. I know that I can use onUnload to catch the unload event and insert my javascript there, but where do I find the URL of the page that is being requested?

I don't care what the page is (reload the current page, new page on same domain, external page, whatever)...I just want the URL.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 29

Accepted Solution

by:
Badotz earned 1000 total points
ID: 20069354
It dependes on how the page is "unloaded". If the user clicked an anchor, then that will be available from the parameter 'e' in the function. If the user clicked the 'x' to close the window, then the element will be the BODY of the document.
0
 
LVL 6

Author Comment

by:karlwilbur
ID: 20069454
<script type="text/javascript" language="javascript">
            function pageUnload(e) {
                  alert(e);
            }
</script>
<body onunload="javascript:pageUnload();">

My alert shows "undefined".
      
0
 
LVL 6

Author Comment

by:karlwilbur
ID: 20069475
The constraints are such that I cannot edit the existing links, onclick, onchange or flash actions. What I need to to is modify the main page with JavaScript to check for what url has been requested.

My guess is that the best place to put such code is in the onUnload event for the body.
0
 
LVL 23

Assisted Solution

by:basicinstinct
basicinstinct earned 1000 total points
ID: 20069595
you could try something along the lines of this approach:

<html>
<head>
      <script type="text/javascript" language="javascript">
            /*
             * Listens to click events
             * and captures the href of any
             * <a> elements clicked
             */
        function pageUnload(e)
        {
                var hrf;
                var el;
                if(e != null)
                {
                      el = e.target;
                }
                else<html>
<head>
      <script type="text/javascript" language="javascript">
            /*
             * Listens to click events
             * and captures the href of any
             * <a> elements clicked
             */
        function pageUnload(e)
        {
                var hrf;
                var el;
                if(e != null)
                {
                      el = e.target;
                }
                else
                {
                      e = window.event;
                      el = e.srcElement;
                }
                if(el != null && el.tagName.toLowerCase() == 'a')
                {<html>
<head>
      <script type="text/javascript" language="javascript">
            /*
             * Listens to click events
             * and captures the href of any
             * <a> elements clicked
             */
        function pageUnload(e)
        {
                var hrf;
                var el;
                if(e != null)
                {
                      el = e.target;
                }
                else
                {
                      e = window.event;
                      el = e.srcElement;
                }
                if(el != null && el.tagName.toLowerCase() == 'a')
                {
                        hrf = el.href;
                }
                if(hrf != null)
                {
                      alert(hrf);
                }
        }
        window.onclick = pageUnload;
      </script>
</head>
<body>
      <a href="http://www.ubuntu.com/">Leave</a>
</body>
</html>
                        hrf = el.href;
                }
                if(hrf != null)
                {
                      alert(hrf);
                }
        }
        window.onclick = pageUnload;
      </script>
</head>
<body>
      <a href="http://www.ubuntu.com/">Leave</a>
</body>
</html>
                {
                      e = window.event;
                      el = e.srcElement;
                }
                if(el != null && el.tagName.toLowerCase() == 'a')
                {
                        hrf = el.href;
                }
                if(hrf != null)
                {
                      alert(hrf);
                }
        }
        window.onclick = pageUnload;
      </script>
</head>
<body>
      <a href="http://www.ubuntu.com/">Leave</a>
</body>
</html>
0
 
LVL 29

Expert Comment

by:Badotz
ID: 20069726
I was hoping the Asker could do it on his own, with a little more research :-/
0
 
LVL 6

Author Comment

by:karlwilbur
ID: 20069880
I have already looked at that. It is not what I am trying to do. I need to be able to capture the URL from any redirection. Not just clicking a link.

That might work if all I were looking for were anchor elements, but I am also looking to capture onclick from all other elements where window.location or document.location is set. as well as events from flash that do the same thing.

I have been looking and looking ... still nothing. I am not looking for code samples. I can write the code myself. I just want to know if there a way to get this data and if so, where. I cannot find anything in the W3C DOM reference.

Also, where did you get 'window.event' and 'window.event.srcElement'? These are not part of the W3C DOM that I have read?

http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-html.html
0
 
LVL 23

Expert Comment

by:basicinstinct
ID: 20069891
badotz - i was answering this post: 20069454 where he was stuck...

karlwilbur - window.event and srcElement are annoying Microsoft features that you need to use in their totally non-standard browser (internet exploder).

the example was just an example - you can trap other tags by adding your own code:

if(el != null && el.tagName.toLowerCase() == 'a')

if(el != null && el.tagName.toLowerCase() == 'SOME OTHER TAG')
0
 
LVL 6

Author Comment

by:karlwilbur
ID: 20069894
Just a little more data:

I have been looking thought the layout engines comparisons from Wikipedia. I know that Trident has limited DOM support so I really need to stick to W3C DOM Level 1. I see potential solutions with W3C DOM Level 3, but that's not really an option.
http://en.wikipedia.org/wiki/Comparison_of_layout_engines_(DOM)

I need to keep it standard. No squirrely Microsofty IE only stuff.  (Though information on how it could be done in such an environment may prove helpful to finding a real solution). However, again, I am limited to W3C DOM Level 1 due to Tridents limitations.
0
 
LVL 6

Author Comment

by:karlwilbur
ID: 20069896
Thanks basicinstinct. I posted my last before I saw your 20069891
0
 
LVL 6

Author Comment

by:karlwilbur
ID: 20069907
basicinstinct, Thanks, but I think that I cannot limit myself to looking thought a bunch of tags. I had considered that originally and determined that it would be too much or try to check for every tag that might fire an event to redirect the page ( e.g. <a> <img> <div> <span> <object> <embed> <select> <li> <tr> <td> and on and on ).

Still looking for something. Will keep you updated.
0
 
LVL 23

Expert Comment

by:basicinstinct
ID: 20070001
ok karl, but i thinkthat's what you're going to have to do!
seeing as you are writing the page you only need to code for the tags that you use to change the location...
0
 
LVL 29

Expert Comment

by:Badotz
ID: 20070614
Please tell us why you need to know where the user wants to go?
0
 
LVL 6

Author Comment

by:karlwilbur
ID: 20071577
Tracking exit point from website. Which external links are followed. I don't care if the type somethinginto their browser or if the follow a link form an email or somthing that takes them from the site. Only interested in  redirection (via anchor tags or javascript) from page content to outsite of the domain.

Normally I could use something like:
<a href="http://host.someotherdomain.tld/" onclick="javascript:myTracker('host.someotherdomain.tld')">SomeOtherDomain</a>

or:
<span class="virtual_link" onclick="myRedirection("host.someotherdomain.tld")">some text here</span>

which would allow me to track this data, but in this particular case I cannot edit the content of the page nor access the embedded flash URLs to include such wrapper functions.

So what I am looking for is something like:
<html>
    <head>
        <script type="application/x-javascript;version=1.1" language="JavaScript1.1">
           function myUnload() {
               newURL = document.newLocation; // I know...newLocation doesn't exist in the DOM
               myTtracker(newURL);
           }
        </script>
    </head>
    <body onUnload="javascript:myUnload;">
        <a href="http://host.someotherdomain.tld/">SomeOtherDomain</a>
    </body>
</html>


0
 
LVL 29

Expert Comment

by:Badotz
ID: 20071759
Then you will have to interrogate the e (event) element and determine what the user clicked from that.
0
 
LVL 6

Author Comment

by:karlwilbur
ID: 20076118
Please correct me if I am wrong, but it appears that targeting the unload event is not going to work. I am not finding sufficient information form my googling sessions and Mozilla/W3C documentation to tell that it is definitely not the way to go. Nor am I finding a clear cut path through unload to get and indication of the new URL.
(using window.onunload rather than window.onclick)

I am having trouble with this one because I have been using Firebug to look through the DOM and on unload, Firebug gets disabled.

The "e" event seems to be DOM Level 2 and I really want to stick with DOM Level 1 due to the constraint of compatibility (not my idea, but a requirement nonetheless ), but to "interrogate the e (event) element" as Badotz suggests seems to be the way to go, but I'll have to attach the same function to many events (onclick, onchange, etc. ) thus having it fire needlessly.

Still looking for the best solution. I'll keep you posted, but still open to any other ideas.

0
 
LVL 29

Expert Comment

by:Badotz
ID: 20076770
Why not implement an unload event in a sample page and see if it works or not. Speculation is, after all, just speculation.
0
 
LVL 6

Author Comment

by:karlwilbur
ID: 20079061
Badotz, That is what I have been doing, but as I mentioned, I cannot dig through the unload event because Firebug seems to become disabled at that point. So, I am left to read the DOM and ECMAScript specifications.

basicinstinct, thank you very much. The code that you gave works great for links. I need to expand it to include other tags as you suggested.

I am also going to have to dig a little deeper though to get tags that already have an onclick that modifies the document.location. Seems as thought these fire before the windows.onclick and I get taken away before I see my alert.

Still working on it. And thanks again to both of you for your help thus far.
0
 
LVL 29

Expert Comment

by:Badotz
ID: 20079445
Add the statement

debugger;

on a separate line in your code and that will allow you to choose yout debugger.
0
 
LVL 6

Author Comment

by:karlwilbur
ID: 20083108
I just came across this in another EE post:

<html>
<head><script>
function fun() {
  document.location.href = document.location.href + "MY TEXT HERE";
}
</script></head>
<body onunload="fun();">
This is a test page.
</body>
</html>


Which based on my earlier sample pages should return to the current page since document.location.href  = current page href, but when I actually tested it, it worked as expected. So I think that I may be getting close to a solution here.
0
 
LVL 23

Expert Comment

by:basicinstinct
ID: 20083299
"Nor am I finding a clear cut path through unload to get and indication of the new URL"

There is no way to find out what the new URL will be unless the new URL is selected from within you page code. To clarify:

1. If a user is on your site and then types a new URL in the address bar THERE IS NO WAY YOU CAN KNOW IT.  Not possible, no way, not on your nelly, forget it.

2. If a user clicks a navigation element in your page then you can code your page in any number of ways to work out if the user is leaving your site.  This is the only time you'll ever know the new URL.

I'd love it if you followed DOM standards strictly and didn't implement window.event.  That would mean you weren't coding your site for Internet Explorer - if you do that on a public site I'll buy you a beer.
0
 
LVL 6

Author Comment

by:karlwilbur
ID: 20083411
basicinstinct,

You are absolutely correct, #1 is a hopeless pursuit. That is not what I am trying to do. I really don't care at all about that. We simply want to know when a user leave the site from one of our links.

I know that there are a number of ways to do anything, what I am looking for is a standards compliant way to get the new URL without having a collection of if..else statements for event and element possible. (Not saying that's what you are suggesting, just that it would work and be very ugly). Looking for something a little more elegant.

The code needs to work in multiple browsers on multiple platforms. I am trying to restrain myself to the DOM Level 1 and ECMAScript (ECMA-262) standards so that it works equally well with Trident/JScript  and Gecko/JavaScript.

I may have to suck it up and go with a solution that only works in IE6, IE7 and FF1.5 on Windows (usually try to use Opera, Safari and Konqueror on Windows and IE5.5, IE6, FF1.5, FF2.0, Konqueror and Galeon on Ubuntu 6.10 as well for my testing). I don't like the idea of having to implement nonstandard solution, but sometime that's what it takes.

It is a rather public site. I'll email you a URL once we push the changes to production.

I won't be able to test my most recent ideas until tomorrow. I'll post my solution then an close out this question. Thanks to both you and Badotz for all of your help.
0
 
LVL 23

Expert Comment

by:basicinstinct
ID: 20083693
the code i posted where you test to see if 'e' is null and if so grab window.event is pretty stock standard code, it is ugly because microsoft built an ugly non-standards compliant browser...

another way i have seen around the traps, i think is uglier but is definitely standards compliant, on any link or object that is internal to your site you set a global javascript variable to flag that it is internal... you can do it the other way around (ie flag on external links)...
0
 
LVL 17

Expert Comment

by:ram_0218
ID: 20115820
what exactly did you implement? can you post the code here?
0
 
LVL 17

Expert Comment

by:ram_0218
ID: 20119622
ok. i've handled this case for the anchor tags but if someone tries to set document.location.href thru javascript function which would be called by clicking on anchor tag, have no clue how to handle that. because right now i handle all the onclick events occuring on this body and get href from the anchor element but when setting the document.location.href thru javascript it invokes the event on the body and the body doesnt have the href attribute. thats the pbm.

i cant change the content because the content is coming from the third party and our portal just handles the menu structure with the content coming from the third party.
0
 
LVL 6

Author Comment

by:karlwilbur
ID: 20547034
Still no real answer to my original question. I recommend closing it with a point split for basicinstinct and Badotz since their solutions will be very helpful to someone somewhere (I'm sure that I will refer back to them in the future at some point). Though, again, there was not real solution to the exact problem that I was dealing with.
0
 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 20547177
In that case you can close this yourself.  Let me know if you have a question about how to split or close this.  Keep in mind that you don't have to award points or close for effort.  I made the recommendation I did based on your replies here but feel free to select the comments that helped you with this issue and close this.

b0lsc0tt
EE Cleanup Volunteer
0
 
LVL 1

Expert Comment

by:Computer101
ID: 20561853
Forced accept.

Computer101
EE Admin
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

JavaScript has plenty of pieces of code people often just copy/paste from somewhere but never quite fully understand. Self-Executing functions are just one good example that I'll try to demystify here.
A while back, I ran into a situation where I was trying to use the calculated columns feature in SharePoint 2013 to do some simple math using values in two lists. Between certain data types not being accessible, and also with trying to make a one to…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question