How to make an external javascript file knows its own host? - javascript

Is there any way that in an external javascript file, can know the host of the file?
For example, if I have the site http://hostOne.com/index.php, the code of the file index.php:
<html>
<head>
<script type="text/javascript" src="http://hostTwo.com/script/test.js"></script>
</head>
<body>
<div>...</div>
</body>
</html>
I need that in the file test.js can know the host http://hostTwo.com.
Thank you.
EDIT
or it can know the tag "script" which was called?, with this option I can analyzes the tag and get the "src" attribute. But I don't want to depend on the name of the file test.js and analyze all the tag script that contains the site.
*Solution based on the code of #Armi *
Html:
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script id="idscript" type="text/javascript" src="http://hostTwo.com/script/test.js"></script>
</head>
<body>
<div>...</div>
</body>
</html>
code in JS
var
url = $('head').find('#idscript').attr('src'),
host = url.replace(/(\/\/.*?\/).*/g, '$1');
console.log(host);

I've got an idea (the snippet based on jQuery):
var yourScriptTag = $('head').find('script[src$="jquery-1.7.1.js"]').eq(0);
var theHostnameOfYourScript = $(yourScriptTag).attr('src').replace(/(http:\/\/.*?\/).*/g, '$1');
alert(theHostnameOfYourScript);
jsfiddle example: http://alpha.jsfiddle.net/XsJn8/
If you know the filename of your script (and if this is always the same and unique) you can use this snippet to get the hostname.
If this path is relative (and contains no host) you can get the hostname with a simple location.hostname

Sorry, not possible. The content of the script is downloaded and after this it is fired. At this point the script "thinks" he is at your site.
Of course unless the host is hardcoded in the script.

This is not possible, because the JavaScript code is executed client-sided. You could propably parse it somehow out of your URL but, I don't think either that this is very useful and possible.

Inside test.js, you can use :
var url = document.URL;
then parse the url result.
You can't make cross-site scripting, so if you need more sophisticated stuff, you could write your javascript in php and call :
<script type="text/javascript" src="http://hostTwo.com/script/test.php"></script>
But that's not standard.
Anyway,, the solution is on the server, with a designed proxy.

Related

[react,ES6]I fail to access object in http script label in index.html , from my own JS page

This is the script in my index.html
<script type="text/javascript" src="http://api.map.baidu.com/api v=2.0&ak=eBGR7XzaPhB5UbYARl3E7ksdkMdgrCw7"></script>
and I try to access a object --"BMap" from the script in my JS page which look like this:
var map = new BMap.Map("allmap"); // 创建Map实例
then I get error:"error! BMap is not defined"
what should I do?
I am guessing that you wanted to use BMap that is provided by baidu api. I changed the src that is actually pointing to the script and it seems to work. Note that you probably want to change the https to http when you are developing locally, as it may not work otherwise. See working example below (I had to use https because stackoverflow uses it by default).
If you have any other js module that uses BMap, make sure that it is called after the baidu api script is declared. S
<html>
<head>
<script type="text/javascript" src="https://api.map.baidu.com/getscript?v=1.1&ak=&services=true&t=20130716024058"></script>
<script type="text/javascript" src="../path/test.js"></script>
<script type="text/javascript" src="../otherpath/someOtherjs.js"></script>
</head>
<body>
<script>
// You can use BMap here...
console.log(BMap);
</script>
</body>
</html>

Javascript include technique with dynamic SRC="url"

Is it possible (and a good idea) to pass dynamic data to a JavaScript include file via a hash url?
Such as:
<head> <script src="scripts.js#x=123&y=456"></script> </head>
I am looking for an alternative to inline js in dynamically built pages:
<head>
<script src="scripts.js#x=123&y=456"></script>
<script>
$( document ).ready(function() {
pageInit(123, 456)
});
</script>
</head>
Is it a good idea to avoid inline js? How can you pass dynamic data without ajax which creates a needless roundtrip network request?
Note: The hash bang url is a special because the browsers ignore the hash portion of the url when checking the cache. At least for html files.
So all of these will reuse the index.html file it is in the cache:
index.html
index.html#x=123
index.html#x=345345
index.html#x=2342&y=35435
This same principle should hold true for javascript files. What I hope to achieve is to reuse the cache version of script.js from page to page.
Going to index.php, include this:
<head> <script src="scripts.js#x=123&y=456"></script> </head>
Then going to fun.php include this
<head> <script src="scripts.js#x=898756465&y=5678665468456"></script> </head>
Then going to see.php include this
<head> <script src="scripts.js#session=887987979&csrf_token=87965468796"></script> </head>
From page view to page view, pass whatever info the page needs via the hash bang while at the same time reuse scirpt.js from cache.
So, is it possible to read the hash bang info from within the scirpts.js?
If the HTML file you are creating is dynamic, then just create inline JavaScript. Writing an include will just create an extra request from the browser, which you can avoid in the first place.
Edit:
just include a JavaScript file that reads the URL, you don't need to pass any variables (but of course, you also could):
$(document).ready(function() {
// pseudo code
hashbang = location.href.substr(location.href.indexOf('#') + 1);
if (hashbang.x && hashbang.y) {
pageInit(hashbang.x, hashbang.y);
} else if (hashbang.csrf_token) {
// do something else
}
});

how to pass value to a js file

I know this question are asked hundreds of times :( but I just want to learn more :).
My question is simple, can I pass a value to a js file like this, if not, how ?
<script type="text/javascript" src="./js/create.js?method=create"></script>
Yes, you notice that I have a parameter method=create which I want to use in my create.js.
I know in jquery ajax, we have an easy way, but you must notice that the ajax method is in included in the js file, how could I pass a parameter to the js file itself ?
Any answer is welcome :)
Thanks.
This works perfect for me:
<script src="js/script.js" id="myScript" data-url="my_variable"></script>
inside the script.js file:
var myUrl = document.getElementById("myScript").getAttribute( "data-url" );
"myUrl = my_variable" inside the code
you can use myUrl everywhere.
Not really, no. What you can do is this:
<script type="text/javascript">
var method = "create";
</script>
<script type="text/javascript" src="./js/create.js"></script>
Another way is to only define functions inside your javascript file, and then invoke after it has loaded.
<script type="text/javascript" src="./js/create.js"></script>
<script type="text/javascript">
runMyLoadedCode("create");
</script>
Third way is belying my first simplistic answer: access the script tag itself and parse it. You can see here how to access the tag that has loaded your script; take its src value and cut it up to locate your method=create.

HTML/Javascript - Get image source from online file

I want to have an image in a webpage that can be changed based on the filepath stored in a file online (it doesn't matter what typer of text file - xml, .txt - whatever works best).
So I basically want to have the page retrieve the text from that file, and then use that text as the source for an image in that page.
I'm assuming this is a Javascript thing, but it doesn't matter to me, as long as it works.
Any ideas?
Thanks!!
**Edit: Forgot to mention: I'm using the code in a Google Chrome Extension, not sure that matters, as it uses regular HTML/Javascript, but it's stored on the users computer, and I want the image to be stored on my server.
**Edit2:
Just got something that seems to work very well, and I only need this in the body part of the code:
<script type="text/javascript" >
var i=0;
for (i=0;i<=FilePath.length - 1;i++)
{
document.write('<img src="' + FilePath[i] + '"/>');
}
</script>
Hope this is valid code, but it definitely seems to work here...
Its simple store the filepaths in a Javascript file , create an array in the JS file , and include all the filepaths in the array, then store the file on the webserver .
Then after that you can retrieve it using
<script src="JS_File_path_on_web_server" type="text/javascript" ></script>
After you retrieve it , you can use Javascript , I prefer jQuery , to replace the src attribute on the Image with the one from the array .
EDIT : Full version :
//Javascript web server File
var FilePath=new Array("Path1","Path2","Path3");
Create a file like this and store as many paths as you want in the array .
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js">
</script>
<script src="JS_File_path_on_web_server" type="text/javascript" ></script>
<script type="text/javascript" >
$(document).ready(function()
{
$('#DisplayImage').attr('src',FilePath[0]);
});
</script>
</head>
<body>
<img src="" id="DisplayImage" />
</body>
</html>
This is a simple example , you can try learning javascript and Jquery to tweak it further .
Since my php based answer was not applicable, we can all ignore it now. :)

Interesting javascript code in configuration options in MathJax

As far as I know the javascript code can be "defined" as file
<script type="text/javascript" src="script.js"></script>
or as inline code
<script type="text/javascript">
....
// some more code
....
</script>
So, how this is done ? Nevertheless this is javascript code !?!
<script type="text/javascript" src="MathJax.js">
MathJax.Hub.Config({
extensions: ["tex2jax.js", "mml2jax.js"],
jax: ["input/Tex", "input/MathML", "output/HTML-CSS"]
});
</script>
Video configuring MathJax
(Found out from looking at MathJax demos with Chrome's developer tools)
It's programmatically creating new <script> tags and places them inside the <head> tag, rather like http://requirejs.org/ or http://headjs.com/ does.
Something along the lines of
var scr = document.createElement('script');
scr.setAttribute('src', 'path/to/script.js');
headDOMnode.appendChild(src); // 'path/to/script.js' starts to load..
happens when MathJax.Hub.Config() executes.
Edit: head.js and require.js does it with rather a lot more bells and whistles, of course.
This is just some invalid markup. Excerpt from specs follows (note the usage of must rather than should):
If the src attribute is not set, user
agents must interpret the contents of
the element as the script. If the src
has a URI value, user agents must
ignore the element's contents and
retrieve the script via the URI.

Categories