Javascript Get Hostname of File Host - javascript

Although this question is similar, it is not what I am looking for.
Let's say on HostA.com I include a script from HostB.com:
<script type="text/javascript" src="http://www.hostb.com/script.js">
When script.js runs, I need to get the name of HostB (let's assume it can change). If I use:
var hostName = window.location.hostname;
It will return HostA.com rather than HostB.com obviously because that is where the the window object is scoped.
How can I get the name of HostB from within the script? Do I have to locate the <script> element in the DOM and parse the src attribute or is there a better way?
EDIT
Yes, it is on my server, but may be on other servers as well. I am developing a javascript plugin and am trying to make absolute paths so it doesn't try to reference files on the server including the plugin.

Here is how: first off, include this as the first line of your script. I know it is a comment. Do it anyways
//BLAHBLAHBLAHBLAHAAABBBCCCDDDEEEFFFGGGILIKEPI
next, use this function inside of that script to determine the host
function findHost(){
var scripts=document.getElementsByTagName('script');
var thisScript=null;
for(var i=0;i<scripts.length;i++){
if(scripts[i].innerHTML.indexOf('//BLAHBLAHBLAHBLAHAAABBBCCCDDDEEEFFFGGGILIKEPI')!==-1)
var thisScript=scripts[i];
}
var urlParser=document.createElement('a');
urlParser.href=thisScript.getAttribute('src');
return urlParser.hostname;
}

I am loading the script with RequireJS which looks something like this:
<script data-main="http://hostb.com/js/app/main.js" src="http://hostb.com/js/vendor/require.js" type="text/javascript"></script>
I figured out, with help from #adeneo that I can do something like this:
$('script[data-main*="/js/app/main.js"]').attr('data-main')
Which returns:
http://hostb.com/js/app/main.js
And I can parse it for the hostname.
var url = $('script[data-main*="/main.js"]').attr('data-main');
parser = document.createElement('a');
parser.href = url;
host = parser.hostname;
Thanks for the suggestions and nudge in the right direction!
BREAKING NEWS
Turns out their is an easier way for anyone using RequireJS (who finds this question in search) and needs to be able to load absolute URL's with the script host:
var myCssPath = require.toUrl('css/mystyles.css');
That builds an absolute path using the hostname of the server running!

To omit using the hostname twice (as you described in your 'accepted answer') I implemented the solution this as follows:
HTML on HostA.com:
<script data-main="my_embed_id" src="http://hostb.com/js/vendor/require.js" type="text/javascript"></script>
require.js on HostB.com:
// get host where this javascript runs
var url = $('script[data-main="my_embed_id"]').attr('src');
var hostb = url.replace(/(\/\/.*?\/).*/g, '$1');
Which returns:
http://hostb.com
Inspired by: How to make an external javascript file knows its own host?

Related

How to get script URL with RequireJS?

When simply loading your script with a <script /> tag, you can retrieve the script URL like this:
var scriptURL = Array.prototype.pop.call ( // get the last...
document.getElementsByTagName ('script') // ...script tag on the page...
).src.split ('?') [0]; // ...take 'src' attribute...
// ...and strip the query string
This is a bit of a hack, but can be very useful sometimes, for a number of reasons (e.g., when there are other resource files script relies on and you don't want to hardcode the path). It works because at the time of execution the last <script /> tag existing on the page is your script.
I'm not sure if that is so when loading scripts with RequireJS. Is there a similar way in RequireJS to retrieve the script URL from inside the module definition?
You can require the module module, which commonly used to pass the special config settings:
define(['module'], function (module) {
console.log(module)
}
This will give you an object holding the id and the uri to the module
To get the URL of current module you can use the below script in requirejs.
define([module/hello], function (hello) {
var currentUrl = location.href;
var moduleUrl = url+require.toUrl("module/hello.js");
alert(moduleUrl);
});

javascript replace string in js file

Ok so another issue i got
I have a js file that i need to include on my page (i dont have access to edit this js file)
Inside that javascript there is a function wich has a line that i need to edit a variable in there.
lets assume:
Code:
var links = [{"offer_id":"1","title":"Text!","url":"http:\/\/www.site.com\/tracker\/1\/?http:\/\/site.com\/click.php?aff=9917&camp=5626&crt=13346&sid=e6a00014f247fe39de1b_1","footer_text":"text","blank_referrer":"1","active":"1","value":"0.40","creation_time":"1327785202"}];
notice : '&sid=e6a00014f247fe39de1b_1'
i need to add something right after sid=
so that i becomes for example:
Code:
&sid=AlssfIT_e6a00014f247fe39de1b_1
i added: AlssfIT_
any ideas how to achieve this ?
i tried something like
Code:
str.replace("&sid=","&sid="+kwd);
right after i "include" the js file but aparently is not working
I think you're going about it the wrong way. If notice is a variable in the global space you can just replace it normally.
window.someObject.notice = window.someObject.notice.replace("&sid=","&sid="+kwd);
This will of course only work if notice is a variable that is navigable to in the global namespace and is not inside a closure. It is inside a closure if it has a var declaration inside a function() {...}
But, assuming that there is global access to that variable, that will be your easiest way to achieve this.
If not, you can try grabbing the contents of the script and executing it hopefully overwriting the original code. This will only work if your script and the script you are fetching are from the same origin (domain, subdomain, port, protocol, a few other things) - it is impossible otherwise due to the _Same Origin Policy_
Assuming you are at the same origin, you could do something like this (using jquery for simplicity)
( function() {
// First we need the url of the script, we can grab it out of the element directly or it can be hard coded
var scriptLocation = $('script#the-id-of-the-script-element').prop('src');
// Now that we have the location fetch the script again so we can get it as plaintext
// this will usually not do another HTTP request since your browser has it cached
$.get(scriptLocation).done(function(text) { // I prefer the deferred syntax as being more explicit, this is equivalent to $.get(scriptLocation, function(text) {
var newText = text.replace("&sid=","&sid="+kwd);
eval(newText);
});
} )()
Something like this could work.
try regex: (not tested)
myregexp = new RegExp("/&sid=/", "gims");
str.replace(myregexp, "&sid=" + kwd);

How to get the currently loading script name and the url variable of the script?

I am loading a script using the script embed tag and I want to get the url variables and the loading script name inside the script. Is it possible? For Example,
<script src="test.js?id=12"></script>
Inside test.js is there any way to get the url variable id?
Any help would be appreciated.
Thanks,
Karthik
Aside from the answers in the linked post, FWIW with Firefox 4 only you can (with caveats); document.currentScript.src which will return the full url, including arguments.
Thanks for all your efforts I have made that working by assigning an id attribute in the script tag and accessed via jQuery,
<script src="test.js?id=12" id="myScript"></script>
var currentScript = $("#myScript").attr('src'); //This will give me my script src
Thanks,
Karthik
If you want to get a variable from the current URL you can use this:
function queryParser(url){
this.get=function(p){return this.q[p];}
this.q={};
this.map=function(url){
url=url || window.location.search.substring(1);
var url=url.split('&');
var part;
for(var i=0;i<url.length;i++){
part=url[i].split('=');
this.q[part[0]]=part[1];
}
}
this.map(url);
}
var query=new queryParser();
// assuming you have ?test=something
alert(query.get('test'));
I recommend you map the result, so you don't re-parse whenever you want to find a specific element.
I don't really know why you'd pass a query string in a script tag like that, unless you specifically want off-site includes with a simple robust system for various effects. Or are actually using PHP to handle that request.
If you want to "send" a variable to one of your scripts, you can always do:
<script type="text/javascript">
var myVar="I'm in global scope, all scripts can access me";
</script>
<script src="test.js?id=12"></script>
If you really need to get the URL of the currently included script, you can use the code supplied by my peers in the other answers, you can then use:
var query=new queryParser(scriptURL);
alert(query.get('id'));// would alert 12 in your case
Navigating through the link on your comments you can get the proper answer.
Anyway, to make things easier:
var allScripts=document.getElementsByTagName('script');
var indexLastScript= allScripts.length -1;
alert (allScripts[indexLastScript].src);
This will show up "test.js?id=12" as a regular String so its up to you to split it in order to get de param.
Hope it helps, I've tried it on the run over the Chrome Javascript Console. :D.

How do I send a document name to a javascript file?

I want to, let's say on index.htm have this:
<html>
<head>
<script type="text/javascript" src="javascriptfile.js"></script>
</head>
</html>
and then have that script return <title>index</title>, and the index being dynamic according to the file name. How can I accomplish this?
You should really be doing this server-side. But if you insist on client-side processing, this should work:
document.write('<title>' +
window.location.pathname.replace(/^(.*\/)?([^\/.]*).*$/, "$2") +
'</title>');
If you do go with this approach, $DEITY will kill a kitten each time someone visits your site.
There are two possible answers :
if you know exactly what pages you have and all pages are static html, don't do that kind of thing. Just put the title in the page, you'll avoid useless delay
in other cases, this is not a job for JS. Use a server-side technology to dynamically create your page.
In short : dynamic ? use server-side language : put title directly in html
// get your filename
var uri = location.href.split("?")[0].split("/");
var filename = uri[uri.length-1];
// get title tag DOMnode
var title = document.getElementByTagName('title')[0];
title.innerText = filename;
You should note that the browser doesn't not really know what the file name is. All its knows is its public location (URL). Having this in mind, you can read the URI from document.location:
https://developer.mozilla.org/en/DOM/document.location
This property returns a Location object:
https://developer.mozilla.org/en/DOM/window.location
The Location object has a pathname property you can parse.

Javascript in Virtual Directory unaware of Virtual Directory

Say I have the site
http://localhost/virtual
where virtual is the virtual directory
I have an Ajax request that is defined in a javascript file using JQuery
$.getJSON("/Controller/Action")
When this is called, the client tries to find the url at the root level i.e.
http://localhost/Controller/Action
If I add the tilde (~) symbol in, it turns into
http://localhost/virtual/~/Controller/Action
It should (if it was to do what I wanted) resolve to
http://localhost/virtual/Controller/Action
Any ideas on how to fix this?
Aku's hint above looked right but it didn't want to work for me. Finally I figured out to use it like this
<script type="text/javascript">
var config = {
contextPath: '<%= #Url.Content("~") %>'
};
</script>
and then in my JavaScript I use it like this
config.contextPath + 'myAppPath".
So in case of no virtual directory this resolves to
"/" + "myAppPath"
and in case of a virtual directory this resolves to
"/VirtualPath/" + + "myAppPath"
and this finally worked for me.
I used this solution successfully
Place the following element in your masterpage
<%= Html.Hidden("HiddenCurrentUrl", Url.Action("Dummy"))%>
Declare a global variable in your main javascript file
var baseUrl = "";
Set baseUrl to the value of "HiddenCurrentUrl" when your javascript is loaded
baseUrl = $("#HiddenCurrentUrl").val();
baseUrl = baseUrl.substring(0, baseUrl.indexOf("Dummy"));
Use baseUrl
$.getJSON(baseUrl + "Action")
EDIT Improved solution
In your controller
ViewBag.BaseUrl = Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath + "/";
In your master page
<script type="text/javascript">
var YourNameSpace = YourNameSpace || {};
YourNameSpace.config = {
baseUrl: "#ViewBag.BaseUrl"
}
</script>
Use your baseUrl
$.getJSON(YourNameSpace.config.baseUrl + "Action")
Another way to get a base url is
<script type="text/javascript">
window.g_baseUrl = '#Url.Content("~")';
</script>
For example, if you run your app from SomeName virtual directory then
window.g_baseUrl variable will be equal to /SomeName/
Benefit of this method is an ability to call actions in the other controllers like so
$.getJSON(window.g_baseUrl + "AnotherController/Action")
Maybe,$.getJSON("Controller/Action") will do?
The tilde shortcut for your application root path is a special feature of ASP.NET, not part of URLs themselves. Consequently trying to use a URL with a tilde in from JavaScript won't resolve the site root, it'll just give you a literal ~ as you can see.
You'd need to pass the value of the application root path to JavaScript so it can construct URLs itself. I'm not that familiar with ASP.NET but I believe you could do something like:
<script type="text/javscript">
var approot= <%= JavaScriptSerializer.Serialize(Request.ApplicationPath) %>;
... $.getJSON(approot+'/Controller/Action') ...;
</script>
A simpler way to do it if you know there's a link on the page to the approot would be to read the href of that link:
var approot= $('#homepagelink').attr('href');
Relative Path to the JS file was the only solution I found
$.getJSON("../Controller/Action")
I know this question is very old but I was lately struggling with this issue and was able to resolve it using
url:'<%=VirtualPathUtility.ToAbsolute("~/Include/cntrols/Data.aspx") %>',
this works great in my ajax call...
It is too late to answer this question. But may be useful to someone as I had same problem. Instead of doing all this steps mentioned in above answers, better way is to use
Url.Action('action','controller').
It'll generate url /VIRDIR/controller/action if it is running from virtual directory or generate /controller/action in other case.

Categories

Resources