In Javascript any way to know what host script was loaded from? - javascript

In javascript, as a script loaded from somer host, is there any way to know what server/host I was loaded from? I need to make additional ajax requests back to that host and would prefer to figure out the host dynamically.
So if you include a javascript file on a page
<script src="http://somehost.com/js/test.js"></script>
when that javascript execute, within test.js ...
var host_loaded_from = ??? // should be somehost.com
Thanks

is there any way to know what server/host I was loaded from?
Yes, it's possible except when the script is loaded asynchronously using defer or async attributes since the last script in the DOM may not necessarily be the currently executing script in that case. See the comments by #kangax for more information.
Also, this same question was posted recently.
Inside your test.js, get the last script element which will be the currently being parsed script (test.js in your case), and get its src.
// test.js
var scripts = document.getElementsByTagName('script');
var src = scripts[scripts.length - 1].src;
One the src is found, parsed the host using regex.
src.match(new RegExp('https?://[^/]*'))
["http://somehost.com"] // for your example

Does the script know its own file name? ("test.js" in the OP question.)
If so, your script could query the dom for all script tags, looking for the ones with a src attribute. But you'd need to watch out for two scripts with the same file name loaded from different servers. Eg
<script src="http://somehost.com/js/test.js"></script>
<script src="http://somehost_number2.com/js/test.js"></script>
Here's JS that looks for all of the script tags in an el:
var scripts = el.getElementsByTagName('SCRIPT');

Nope, sorry.
If the <script> had an id, then maybe. But you can't really rely on that.

Not sure if that can be done with JavaScript. If the script is inside a PHP file do it like this:
...
var host_loaded_from = <?php echo $_SERVER[SERVER_NAME] ?>
...
On my site I include my JS scripts using PHP just for that reason. I'm interested to see if there's a better way.

Due to Same Origin Policy, you can make AJAX requests only to the origin (host + protocol + port), the HTML page (document) was loaded from - which is not necessarily the same as the origin your js was loaded from.
You can use window.location.hostname or document.location.hostname to find out the hostname of the document.

Related

Reload the same javascript file when loading each static page

I have a few static html pages. All these pages have the following
<script src="my-javascript.js"></script>
I don't want the browser to cache the javascript file, and I want it to get reloaded at page load for each page.
After online search, I found that this trick: adding the following to each page
<script src="my-javascript.js?p=changing_value"></script>
If this is going to work, how can I generate the "changing_value" in a static html page (not PHP, JSP, etc.).
Or some other solutions to force reload the javascript file at each page load for all pages?
Thanks!
UPDATE
I dont have access to server configuration.
After online search, I found that this trick: adding the following to each page
A much better solution is to use caching headers to tell the browser not to cache the file. Configure your server to serve that file with:
Cache-Control: no-cache
Expires: -1
Those are the basic ones, anyway.
If this is going to work, how can I generate the "changing_value" in a static html page (not PHP, JSP, etc.).
If you want to go the query string route, though, just for completeness:
You can get a random value from Math.random(), or as Hemadeus points out, use a timestamp value.
If you need the script load to be blocking (like script tags normally are), this is one of the few remaining use cases for document.write:
<script>
document.write('<script src="my-javascript.js?' + Math.random() + '"><\/script>');
</script>
(Or replace Math.random() with Date.now() to use a timestamp)
If you don't need it to be blocking, then creating the element with createElement is probably cleaner:
<script>
(function() {
var s = document.createElement('script');
s.src = "my-javascript.js?" + Math.random();
document.querySelector("head").appendChild(s);
})();
</script>
Old browsers won't have Date.now. You can get the same value from new Date().getTime().
You could generate the changing_value using a Javascript timestamp.
so you will always have a new version of the js file.

Is it possible to get the text of a script that is loaded from a source as opposed to in line code?

Currently I'm just taking source of a script that is on the page.
The HTML:
<script type="text/plain">meow</script>
The JavaScript:
// returns "meow"
document.querySelector('script').text
I want to be able to load the script from another file.
The HTML:
<script type="text/plain" src="file.txt"></script>
file.txt:
meow
The JavaScript:
// returns "meow"
document.querySelector('script').textFromFile
Does anyone know if that's possible? I would assume it's not, and I haven't found anything on google that is what I'm asking.
If the script has a src attribute you would need to fire of a request via XHR to that same path and pull in the text content of its response. Keep in mind this will require additional work if the script is being loaded from another domain. At that point you would need to make use of CORS, or introduce some other type of proxy to handle the cross-domain communication.

How to call a function only when all scripts are loaded?

I am sharing a script tag with client to deploy my web application on client's website.
Basically by this way, he can embed my app wherever he want on his site.
The script which I give him just calls one action method in my MVC application and receives a javaScript as a response.
As a fist step, this returned JavaScript inserts all js and css references (required by my application) in the client's head tag
function createScriptElement(src) {
var tmp = document.createElement("script");
tmp.src = src;
var head = document.getElementsByTagName("head")[0];
head.appendChild(tmp);
};
and then in second step, it writes the html content inside one dynamic div.
document.write(format("<div id='mycontainer'>{0}</div>{1}", AppHtml,initcalls ));
The "initcalls" contains the initial function in my app's javascript which I expect to execute immediately. So I put it in Script tag as below.
contents of initcalls are:
<script type=\"text/javascript\"> function icInitApp() { ..... }; </script>
The problem is: there are some dependencies in my application on the js references. The HTML is getting loaded before the head tag in client's page recognizes and loads the js references.
Is there any way to hold my (thus dynamically rendered) application's init function until all js references are fully loaded by head tag?
I tried giving setTimeout() with 5 seconds but it will not be proper solution accepted by client.
A similar kind of situation is discussed in the link below
How to detect if javascript files are loaded?
You can also try to use the $(window).load() event since this will be fired when the page is fully loaded.
$(window).load(function(){
//your code here
});
PS: Be aware that you will need to load the jQuery in your page to make the above code work.
You can try with jQuery:
$(document).ready(function()){
// Your code goes here
};

How to load a script file and execute it?

I have feedburner script which displays feeds, it looks like this:
<script src="http://feeds.feedburner.com/cnn/HIkg?format=sigpro" type="text/javascript" ></script>
I want to load this script which is on a different html page, so basically I'm loading html file with this script in it using:
$('#' + items[i]).load('content/' + items[i] + '.html');
This piece of code does load the html page but the script is not executed(working). How do I get the script to work once loaded?
According to the documentation :
Script Execution
When calling .load() using a URL without a suffixed
selector expression, the content is passed to .html() prior to scripts
being removed. This executes the script blocks before they are
discarded. If .load() is called with a selector expression appended to
the URL, however, the scripts are stripped out prior to the DOM being
updated, and thus are not executed.
If your url is just a plain url without a selector specified than the script should execute before it is removed.
Check the value of items[i] and check if it is a plain url without a selector or not.
If the url looks fine, you might be running into a cross-side scripting issue. The documentation also mentions:
Due to browser security restrictions, most "Ajax" requests are subject
to the same origin policy; the request can not successfully retrieve
data from a different domain, subdomain, or protocol.
If possible though I still would recommend for any script to be in an external file as that is good practice and doesn't clutter the html. Then you can use .getScript() as recommended by Raminson.
You can use the $.getScript() utility function:
Load a JavaScript file from the server using a GET HTTP request, then execute it.
$.getScript("/test.js")

Executing a JavaScript file directly from the browser

This sounds like a trivia question but I really need to know.
If you put the URL of an HTML file in the Location bar of your browser, it will render that HTML. That's the whole purpose of a browser.
If you give it a JPG, or a SWF, or even PDF, it will do the right things for those datatypes.
But, if you give it the URL of a JavaScript file, it will display the text of that file. What I want is for that file to be executed directly.
Now, I know that if you use the javascript: protocol, it will execute the text of the URL, but that isn't what I need.
I could have the URL point to an HTML file consisting of a single <script> tag that in turn points to the JavaScript file, but for occult reasons of my own, I cannot do that.
If the file at http://example.com/file.js consists entirely of
alert("it ran");
And I put that URL in the Location bar, I want "it ran" to pop up as an alert.
I'm skeptical that this is possible but I'm hoping-against-hope that there is a header or a MIME type or something like that that I can set and miraculously make this happen.
This is not possible. The browser has no idea what context the JavaScript should run in; for example, what are the properties of window? If you assume it can come up with some random defaults, what about the behavior of document? If someone does document.body.innerHTML = "foo" what should happen?
JavaScript, unlike images or HTML pages, is dependent on a context in which it runs. That context could be a HTML page, or it could be a Node server environment, or it could even be Windows Scripting Host. But if you just navigate to a URL, the browser has no idea what context it should run the script in.
As a workaround, perhaps use about:blank as a host page. Then you can insert the script into the document, giving it the appropriate execution context, by pasting the following in your URL bar:
javascript:(function () { var el = document.createElement("script"); el.src = "PUT_URL_HERE"; document.body.appendChild(el); })();
Or you can use RunJS: https://github.com/Dharmoslap/RunJS
Then you will be able to run .js files just with drag&drop.
Not directly, but you could make a simple server-side script, e.g. in PHP. Instead of
http://example.com/file.js
, navigate to:
http://localhost/execute_script.php?url=http://example.com/file.js
Of course, you could smallen this by using RewriteRule in Apache, and/or adding another entry in your hosts file that redirects to 127.0.0.1.
Note that this is not great in terms of security, but if you use it yourself and know what you're downloading, you should be fine.
<html>
<head>
<script>
<? echo file_get_contents($_GET['url']); ?>
</script>
</head>
<body>
</body>
</html>
In the address bar, you simply write
javascript:/some javascript code here/;void(0);
http://www.javascriptkata.com/2007/05/01/execute-javascript-code-directly-in-your-browser/
Use Node.js.
Download and install node.js and create a http/s server and write down what you want to display in browser.
use localhost::portNumber on server as url to run your file.
refer to node js doc - https://nodejs.org/dist/latest-v7.x/docs/api/http.html
Run - http://localhost:3000
sample code below :
var http = require("http");
var server = http.createServer(function(req,res){
res.writeHead(200,{'Content-Type':'text/html'});
res.end("hello user");
}); server.listen(3000);`
you can write your own browser using qt /webkit and do that.
when user enters a js file in url location you can read that file and execute the javascript .
http://code.google.com/apis/v8/get_started.html is another channel.
not sure if it meets ur need.

Categories