views:

76

answers:

5

An external javascript can be used by many Web pages. How to know which web page is using an external js script? For example, I've got a javascript script s.js. Is it possible that a function of s.js can check which page is using s.js?

+1  A: 

The JavaScript must be included in a page to be executed. For testing purposes only, you can get the page use this:

document.write(location.href);

In a production environment, store the location in a variable.

var loc = location.href;
SimpleCoder
That's really not a good way to do it at all.
Pointy
So what would you recommend?
SimpleCoder
Well I certainly wouldn't write the URL into the document; I mean, why *would* you do that?
Pointy
It's a demonstration. If you read my post correctly, I said "To get the page use this:" which is all the asker requested.
SimpleCoder
OK, time for some prozac. **Obviously** `document.write` is only there for testing purposes. It could have easily been `console.log` or `alert`. No need to get pedantic about it.
Igor Zevaka
Well OK fine, but seriously using `document.write` *at all* is generally regarded as bad practice, and in this case it's almost certainly not what *anybody* would ever do with the page URL. This site is supposed to serve not only the direct needs of people asking questions, but also people looking for answers that are already posted. Thus, an "example" in an answer should be a *good* example.
Pointy
+1 for applying prozac.
Thqr
+1 for pointing out *good* example
Thqr
Again, it's for demonstration only. I never suggested using document.write in a production environment. Did the asker supply enough information for a more sophisticated example? No. À la document.write(location.href);
SimpleCoder
SimpleCoder, I understood what you meant. I think the `document.write` just confused everyone. You should just make it `location.href`
Armando
Thank you, I have modified my post.
SimpleCoder
I like the bolding of *For testing purposes only*
Thqr
+6  A: 

location object has all the information about the URL the browser is currently on.

    hash        Returns the anchor portion of a URL
    host        Returns the hostname and port of a URL
    hostname    Returns the hostname of a URL
    href        Returns the entire URL
    pathname    Returns the path name of a URL
    port        Returns the port number the server uses for a URL
    protocol    Returns the protocol of a URL
    search      Returns the query portion of a URL

EDIT Now, to answer the question that you actually meant to ask and that is how to track which pages are using your javascript file. I think (and I haven't implemented something like this before) is to use the same strategy as what the analytics sites use.

They all seem to use a variation of a tracking pixel where the browser downloads a script file (e.g. QuantServer - http://edge.quantserve.com/quant.js). The script then requests a 1x1 pixel from the google server and encodes the URL of the webpage into the address of the image. So for stackoverflow.com, the pixel URL is:

http://pixel.quantserve.com/pixel;r=3547206;fpan=0;fpa=P0-82955756-1264139666260;ns=0;url=http%3A%2F%2Fstackoverflow.com.... (I didn't reveal the address as it my browser sends it as I don't really know what it reveals about me :) ).

As you can see, the site's url is a part of the image url. On the server side you would need to have a handler that serves this image and logs the page address by extracting it from the image URL.

The reason for why this is an image and not an AJAX request is because AJAX requests are subject to browser XSS restrictions. Basically, a browser will not make an AJAX call to a website that is not the one serving the page. This means that a page on www.otherpeopleswebsite.com is not allowed to make an AJAX call to www.mywebsite.com. There is no such restrictions on images (or javascript files for that matter).

So a simple system for implementing something like this would do something to this effect:

//s.js
var oldLoad = window.onload;
window.onload = function(){
  if (oldLoad)
    oldLoad();
    var img = document.createElement('img');
    img.setAttribute('src', 'www.mysite.com/pixel?url=' + window.location.href);
}

On the server side, pixel handler would serve a 1x1px image, set the content type to the appropriate value (ie image/gif), extract the query string and log the URL. Depending on you server technology, there are many ways to implement that.

Igor Zevaka
Definently works better than an ajax request.
Thqr
+1  A: 

The script can refer to document.location, which will always be built around the URL of the main page. Specifically, document.location.href will be the URL.

Thus:

if (document.location.href === 'http://www.cnn.com') {
  // being imported by CNN ...
}

or whatever.

Pointy
Lol at everyone getting stuck on location he just wanted to know what pages actually contain the s.js and I think the only way to do that is go through everypage and check yourself. ^^
Thqr
... what? I have no idea what that comment means, @Ozaki. If I've got a script hosted on some site, how could I possibly check "every page"? Google search for the script tag?
Pointy
+2  A: 

Inside your javascript file you need an AJAX call to a script that will log the file name. The log could be to a database or a flat file. You need to send location.href (or a property of location that suits what you're looking for) as a parameter to your logging script.

Embedded in the Javascript file you'll want to attach the function to the windows onload or domready event, to assure that the AJAX call is executed. Make sure not to override the onload/domready event, but just to add it to the event stack. You'll need to lookup how to add/attach an event, if you don't know how to do this.

Note: instead of having a logging script, you could use SOAP or REST to do the logging.

vol7ron
-1 That doesn't make sense. Why would you want to make an ajax call if you can get at location.href from the script.
Igor Zevaka
Because sometimes there are HTML pages that you don't own, that are using your script. You need to write to your log somehow... that's why you use AJAX. Where are you going to send that location.href, give me my point back.
vol7ron
+1 That does make sense if you are hosting say a library online and you want to know how often it gets requested etc that would do the job.
Thqr
Thanks guys. Armando, I don't think he's retarded, I just don't think he understands. The asker wanted to know what page was using it. That could be of his website, or another one. Having a log is the best way to see the history of your scripts and to see if any pages are using any out of date scripts.
vol7ron
How much fun. No, I will not give you your point back. For starters, the question asks *is it possible that function of s.js can check which page is using s.js*. You are answering the question of *how can the server know what web pages are using this javascript*. Since it is an accepted answer, it is what the OP **meant** to ask (but didn't). Also, AJAX calls (i.e. `XMLHttpRequest`) are subject to same origin policy, so a page on someone else's server **cannot** make an ajax request back to your server. For this purpose you need to use something like JSONP.
Igor Zevaka
There's no indication in the original question that the script requester needs to be stored on the server. If it does, then this answer makes some sense. However, it's *not* correct that the function to run the AJAX call would need to be attached to the "load" or "ready" event handlers - there's no reason to wait. The script could run the AJAX call whenever it wanted to.
Pointy
**@Pointy:** It depends on how the user loads loads the script file. The point is that you want to load the file ASAP. You're right, running it instantly is good, but I try to be unobtrusive and usually let things load as they should as to work seamlessly in the background of the other page. I guess it depends on how bad you want to see the file and how much of an impact you want to have on their page loads.
vol7ron
**@Igor Zevaka:** You are correct in that JSONP is a viable option, however this could also be handled with AJAX, especially using SOAP/RESTful web services - it's a moot point if this is on the same domain, such as intranets. -- As for the question, I guess I just inferred something a little more practical. Not saying my answer is the right answer, just a little more how-to for the question I saw. You can be stubborn if you don't want to credit back the point, I don't mind, it's your decision to say my answer wasn't helpful.
vol7ron
+1  A: 

When the script runs on a page you can create an alert (popup menu) to let you know it is on the page you are currently on:

alert('Im in your page being your s.js file');
Thqr