Link to home
Start Free TrialLog in
Avatar of karlwilbur
karlwilbur

asked on

Getting new url href from current page using javascript

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?
Avatar of Badotz
Badotz
Flag of United States of America image

Create a handler for the window.unload event and check the event object for the <a> tag.

IE:
win_unload(e)
{
    // do whatever here...
}
Granted, this is only pseudocode, but if you search Google for 'window.unload', you should find something to help you.
Avatar of karlwilbur
karlwilbur

ASKER

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.
ASKER CERTIFIED SOLUTION
Avatar of Badotz
Badotz
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
<script type="text/javascript" language="javascript">
            function pageUnload(e) {
                  alert(e);
            }
</script>
<body onunload="javascript:pageUnload();">

My alert shows "undefined".
      
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.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I was hoping the Asker could do it on his own, with a little more research :-/
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
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')
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.
Thanks basicinstinct. I posted my last before I saw your 20069891
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.
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...
Please tell us why you need to know where the user wants to go?
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>


Then you will have to interrogate the e (event) element and determine what the user clicked from that.
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.

Why not implement an unload event in a sample page and see if it works or not. Speculation is, after all, just speculation.
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.
Add the statement

debugger;

on a separate line in your code and that will allow you to choose yout debugger.
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.
"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.
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.
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)...
what exactly did you implement? can you post the code here?
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.
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.
Avatar of b0lsc0tt
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
Forced accept.

Computer101
EE Admin