Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can code in a Javascript file know its own domain/URL

Tags:

If I have a site, example.com, and a page on that site references a Javascript at subdomain.example.com/serveAd.js -- is there a way from within serveAd.js to know its own URL, or the domain from which it was downloaded?

(The JS can certainly know all about the page that called it. I want to know if the JS knows about its own origin.)

like image 354
Matt Sherman Avatar asked Jun 22 '10 22:06

Matt Sherman


People also ask

How do I get the URL of a JavaScript file?

To retrieve just the URL as a string, the read-only document. URL property can be used. Sun reference: Do not use location as a property of the document object; use the document. URL property instead.

How do you check if a URL exists or returns 404 with JavaScript?

open('GET', 'http://www.mozilla.org', true); request. onreadystatechange = function(){ if (request. readyState === 4){ if (request. status === 404) { alert("Oh no, it does not exist!"); } } }; request.

Can I write JavaScript both within HTML and also as a separate file?

JavaScript in <head> or <body> You can place any number of scripts in an HTML document. Scripts can be placed in the <body> , or in the <head> section of an HTML page, or in both.


1 Answers

If you were using jquery, you could get the full url with this kind of thing:

var fullJsUrl= $('script[src$=serveAd.js]').attr('src');

If not using jquery, it may take more work, but you get the idea ;)

like image 91
laher Avatar answered Sep 23 '22 13:09

laher