Can JavaScript access it's own source url? - javascript

Suppose I'm embedding a javascript in HTML page:
<script type="text/javascript" src="www.mydomain.com/script.js?var1=abc&var2=def"></script>
Is there a way I can get the src url inside the script and extract the params?

Given that you are using a regular script element in the HTML source, you can just get the last script element in the document. Since script elements are (in the absence of attributes that you aren't using in your example) blocking, no more will be added to the document until this one has been executed.
var scripts = document.getElementsByTagName('script');
var last_script = scripts[scripts.length - 1];
var url = script.src;
This won't work if you dynamically add a script element before the last script using DOM.

this little hack uses error handling to find the location of external scripts from within:
(function(){ // script filename setter, leaves window.__filename set with active script URL.
if(self.attachEvent){
function fn(e,u){self.__filename=u;}
attachEvent("onerror",fn);
setTimeout(function(){detachEvent("onerror", fn)},20);
eval("gehjkrgh3489c()");
}else{
Object.defineProperty( window, "__filename", { configurable: true, get:function __filename(){
try{document.s0m3741ng()}catch(y){
return "http://" +
String(y.fileName || y.file || y.stack || y + '')
.split(/:\d+:\d+/)[0].split("http://")[1];
}
}})//end __filename
}//end if old IE?
}());
it sets a global "__filename" property when run, so atop an external script, the __filename is in effect for the execution of the whole script.
i strongly prefer to sniff url parts from scr attributes, but this works in most browsers and without knowing the URL ahead of time.

I don't think there is a property already inside the script that points to this url.
From the script, you can read the DOM. So you can lookup the script tag and inspect its src attribute, but if you got multiple scripts (or the DOM was modified), you cannot really know for sure which one it is.
I assume it is for checking input. So to solve this, you can eiter:
Render the script through a server side script (PHP), and let it output variables. Disadvantage: eats more server resources and makes caching a bitch.
Just get parameter from all the scripts loading from your domain. Maybe it doesn't matter much, or you have only one script anyway. Disadvantage: In this case this is possible, but not very reliable and resistant to changes.
My preferred: Add the variables to the script tag (actually, to another script tag) to make them available directly in Javascript, rather than parsing the script url.
Like this:
<script type="text/javascript">
var1 = 'abc';
var2 = 'def';
</script>
<script type="text/javascript" src="www.mydomain.com/script.js"></script>

Here are two other solutions that will work no matter how the script is loaded (even if they are loaded dynamically or with async or defer attributes):
Put an id on the script tag.
<script id="myscript" type="text/javascript" src="www.mydomain.com/script.js?var1=abc&var2=def"></script>
Then, you can find it with the id:
$("#myscript").attr("src")
Or second, if you know the filename, you can search for any script tag that contains that filename:
function findScriptTagByFilename(fname) {
$("script").each(function() {
if (this.src.indexOf(fname) !== -1) {
return this.src;
}
});
}
var url = findScriptTagByFilename("/script.js");

Related

HTML Iframes overwrite document.write

Main context
I inject a js script in every HTML page through a proxy
My js code is the first evaluated script in the page
I can modify the page with the proxy
My goal is to add a dynamic attribute to every scripts generated client side before the execution.
All function overwrites work properly except for the write function
The page could have IFrame nodes statically or dynamically generated (or modifed!) which use the write function.
Code
In my injected script there is this code which overwrites the native write function, checks the content, if there are script tags it adds an attribute and recall the original function:
...
var TYPE_WRITE = "type_write";
var f_write = HTMLDocument.prototype.write;
HTMLDocument.prototype.write = function () {
arguments = my_mitm_function(arguments, TYPE_WRITE);
return f_write.apply(this, arguments);
};
...
Problems
It works perfectly except in case of "write" in a "IFrame", here an example:
...
var myIFrame = document.createElement("iframe");
document.body.appendChild(myIFrame);
myIFrame = (myIFrame.contentWindow) ? myIFrame.contentWindow : (myIFrame.contentDocument.document) ? myIFrame.contentDocument.document : myIFrame.contentDocument;
myIFrame.document.open();
myIFrame.document.write("<script>alert('Msg from inside');<\/script>");
myIFrame.document.close();
...
I think the problem is that every IFrame have a different document
Is there a way to hook every "write" function in every "IFrame" context?
or a way to get around ?
More details
I need to add a "nonce" attribute because the CSP policy of the page does not allow scripts but only "nonce" attributes.
I already tested other alternative such as 'MutationObserver' but my function must add the attribute before the CSP engine evalutation.

Get script content [duplicate]

If I have a script tag like this:
<script
id = "myscript"
src = "http://www.example.com/script.js"
type = "text/javascript">
</script>
I would like to get the content of the "script.js" file. I'm thinking about something like document.getElementById("myscript").text but it doesn't work in this case.
tl;dr script tags are not subject to CORS and same-origin-policy and therefore javascript/DOM cannot offer access to the text content of the resource loaded via a <script> tag, or it would break same-origin-policy.
long version:
Most of the other answers (and the accepted answer) indicate correctly that the "correct" way to get the text content of a javascript file inserted via a <script> loaded into the page, is using an XMLHttpRequest to perform another seperate additional request for the resource indicated in the scripts src property, something which the short javascript code below will demonstrate. I however found that the other answers did not address the point why to get the javascript files text content, which is that allowing to access content of the file included via the <script src=[url]></script> would break the CORS policies, e.g. modern browsers prevent the XHR of resources that do not provide the Access-Control-Allow-Origin header, hence browsers do not allow any other way than those subject to CORS, to get the content.
With the following code (as mentioned in the other questions "use XHR/AJAX") it is possible to do another request for all not inline script tags in the document.
function printScriptTextContent(script)
{
var xhr = new XMLHttpRequest();
xhr.open("GET",script.src)
xhr.onreadystatechange = function () {
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log("the script text content is",xhr.responseText);
}
};
xhr.send();
}
Array.prototype.slice.call(document.querySelectorAll("script[src]")).forEach(printScriptTextContent);
and so I will not repeat that, but instead would like to add via this answer upon the aspect why itthat
Do you want to get the contents of the file http://www.example.com/script.js? If so, you could turn to AJAX methods to fetch its content, assuming it resides on the same server as the page itself.
Update: HTML Imports are now deprecated (alternatives).
---
I know it's a little late but some browsers support the tag LINK rel="import" property.
http://www.html5rocks.com/en/tutorials/webcomponents/imports/
<link rel="import" href="/path/to/imports/stuff.html">
For the rest, ajax is still the preferred way.
I don't think the contents will be available via the DOM. You could get the value of the src attribute and use AJAX to request the file from the server.
yes, Ajax is the way to do it, as in accepted answer. If you get down to the details, there are many pitfalls. If you use jQuery.load(...), the wrong content type is assumed (html instead of application/javascript), which can mess things up by putting unwanted <br> into your (scriptNode).innerText, and things like that. Then, if you use jQuery.getScript(...), the downloaded script is immediately executed, which might not be what you want (might screw up the order in which you want to load the files, in case you have several of those.)
I found it best to use jQuery.ajax with dataType: "text"
I used this Ajax technique in a project with a frameset, where the frameset and/or several frames need the same JavaScript, in order to avoid having the server send that JavaScript multiple times.
Here is code, tested and working:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">
<html>
<head>
<script id="scriptData">
var scriptData = [
{ name: "foo" , url: "path/to/foo" },
{ name: "bar" , url: "path/to/bar" }
];
</script>
<script id="scriptLoader">
var LOADER = {
loadedCount: 0,
toBeLoadedCount: 0,
load_jQuery: function (){
var jqNode = document.createElement("script");
jqNode.setAttribute("src", "/path/to/jquery");
jqNode.setAttribute("onload", "LOADER.loadScripts();");
jqNode.setAttribute("id", "jquery");
document.head.appendChild(jqNode);
},
loadScripts: function (){
var scriptDataLookup = this.scriptDataLookup = {};
var scriptNodes = this.scriptNodes = {};
var scriptNodesArr = this.scriptNodesArr = [];
for (var j=0; j<scriptData.length; j++){
var theEntry = scriptData[j];
scriptDataLookup[theEntry.name] = theEntry;
}
//console.log(JSON.stringify(scriptDataLookup, null, 4));
for (var i=0; i<scriptData.length; i++){
var entry = scriptData[i];
var name = entry.name;
var theURL = entry.url;
this.toBeLoadedCount++;
var node = document.createElement("script");
node.setAttribute("id", name);
scriptNodes[name] = node;
scriptNodesArr.push(node);
jQuery.ajax({
method : "GET",
url : theURL,
dataType : "text"
}).done(this.makeHandler(name, node)).fail(this.makeFailHandler(name, node));
}
},
makeFailHandler: function(name, node){
var THIS = this;
return function(xhr, errorName, errorMessage){
console.log(name, "FAIL");
console.log(xhr);
console.log(errorName);
console.log(errorMessage);
debugger;
}
},
makeHandler: function(name, node){
var THIS = this;
return function (fileContents, status, xhr){
THIS.loadedCount++;
//console.log("loaded", name, "content length", fileContents.length, "status", status);
//console.log("loaded:", THIS.loadedCount, "/", THIS.toBeLoadedCount);
THIS.scriptDataLookup[name].fileContents = fileContents;
if (THIS.loadedCount >= THIS.toBeLoadedCount){
THIS.allScriptsLoaded();
}
}
},
allScriptsLoaded: function(){
for (var i=0; i<this.scriptNodesArr.length; i++){
var scriptNode = this.scriptNodesArr[i];
var name = scriptNode.id;
var data = this.scriptDataLookup[name];
var fileContents = data.fileContents;
var textNode = document.createTextNode(fileContents);
scriptNode.appendChild(textNode);
document.head.appendChild(scriptNode); // execution is here
//console.log(scriptNode);
}
// call code to make the frames here
}
};
</script>
</head>
<frameset rows="200pixels,*" onload="LOADER.load_jQuery();">
<frame src="about:blank"></frame>
<frame src="about:blank"></frame>
</frameset>
</html>
related question
.text did get you contents of the tag, it's just that you have nothing between your open tag and your end tag. You can get the src attribute of the element using .src, and then if you want to get the javascript file you would follow the link and make an ajax request for it.
In a comment to my previous answer:
I want to store the content of the script so that I can cache it and use it directly some time later without having to fetch it from the external web server (not on the same server as the page)
In that case you're better off using a server side script to fetch and cache the script file. Depending on your server setup you could just wget the file (periodically via cron if you expect it to change) or do something similar with a small script inthe language of your choice.
if you want the contents of the src attribute, you would have to do an ajax request and look at the responsetext. If you where to have the js between and you could access it through innerHTML.
This might be of interest: http://ejohn.org/blog/degrading-script-tags/
I had a same issue, so i solve it this way:
The js file contains something like
window.someVarForReturn = `content for return`
On html
<script src="file.js"></script>
<script>console.log(someVarForReturn)</script>
In my case the content was html template. So i did something like this:
On js file
window.someVarForReturn = `<did>My template</div>`
On html
<script src="file.js"></script>
<script>
new DOMParser().parseFromString(someVarForReturn, 'text/html').body.children[0]
</script>
You cannot directly get what browser loaded as the content of your specific script tag (security hazard);
But
you can request the same resource (src) again ( which will succeed immediately due to cache ) and read it's text:
const scriptSrc = document.querySelector('script#yours').src;
// re-request the same location
const scriptContent = await fetch(scriptSrc).then((res) => res.text());
If you're looking to access the attributes of the <script> tag rather than the contents of script.js, then XPath may well be what you're after.
It will allow you to get each of the script attributes.
If it's the example.js file contents you're after, then you can fire off an AJAX request to fetch it.
It's funny but we can't, we have to fetch them again over the internet.
Likely the browser will read his cache, but a ping is still sent to verify the content-length.
[...document.scripts].forEach((script) => {
fetch(script.src)
.then((response) => response.text() )
.then((source) => console.log(source) )
})
Using 2008-style DOM-binding it would rather be:
document.getElementById('myscript').getAttribute("src");
document.getElementById('myscript').getAttribute("type");
You want to use the innerHTML property to get the contents of the script tag:
document.getElementById("myscript").innerHTML
But as #olle said in another answer you probably want to have a read of:
http://ejohn.org/blog/degrading-script-tags/
If a src attribute is provided, user agents are required to ignore the content of the element, if you need to access it from the external script, then you are probably doing something wrong.
Update: I see you've added a comment to the effect that you want to cache the script and use it later. To what end? Assuming your HTTP is cache friendly, then your caching needs are likely taken care of by the browser already.
I'd suggest the answer to this question is using the "innerHTML" property of the DOM element. Certainly, if the script has loaded, you do not need to make an Ajax call to get it.
So Sugendran should be correct (not sure why he was voted down without explanation).
var scriptContent = document.getElementById("myscript").innerHTML;
The innerHTML property of the script element should give you the scripts content as a string provided the script element is:
an inline script, or
that the script has loaded (if using the src attribute)
olle also gives the answer, but I think it got 'muddled' by his suggesting it needs to be loaded through ajax first, and i think he meant "inline" instead of between.
if you where to have the js between and you could access it through innerHTML.
Regarding the usefulness of this technique:
I've looked to use this technique for client side error logging (of javascript exceptions) after getting "undefined variables" which aren't contained within my own scripts (such as badly injected scripts from toolbars or extensions) - so I don't think it's such a way out idea.
Not sure why you would need to do this?
Another way round would be to hold the script in a hidden element somewhere and use Eval to run it. You could then query the objects innerHtml property.

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);
});

JSON Object passed to External JavaScript

I was looking at FireBug Lite and saw that they use a pretty cool technique to pass options into an external script file:
<script type="text/javascript" src="https://getfirebug.com/firebug-lite.js">
{
overrideConsole: false,
startInNewWindow: true,
startOpened: true,
enableTrace: true
}
</script>
What is the name of this technique and how does it work?
It's not an automatic variable-passing-technique as you may think.
All their code does is loop through all the script tags until they find the one which loaded their code (by comparing the src attribute to a regular expression (/(firebug-lite(?:-\w+)?(?:\.js|\.jgz))(?:#(.+))?$/;).
If it finds the tag, it simply gets the .innerHTML of the script tag, and evaluates it.
I guess this (unnamed) techique isn't relevant in the real-world, as we don't have a guaranteed method of finding which script tag refers to our library (especially as it is common for all script's to be combined into one script file on live servers).
Furthermore, I have my doubts over how cross-browser this is; as it certainly doesn't go by the spec, which states:
Having said that (and thought about it): the spec states that the browser shouldn't interpret both. However this isn't relevant with this technique. The browser doesn't have to interpet both, as the content of the script is read in through innerHTML (and even if it did read in the content, it doesn't do any harm anyway). Aslong as the browser conforms to the spec, and loads the URI (which all browsers do), there's no problem! (apart from not knowing/ guaranteeing which script tag your library belongs to).
The script may be defined within the
contents of the SCRIPT element or in
an external file. 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.
(i.e., don't interpret both).
Further to #Matt's answer, and to clarify my comment:
var doc = Firebug.browser.document;
var script = doc.getElementsByTagName("script")[index];
var url = getScriptURL(script);
var isExternal = url && url != doc.location.href;
try
{
if(isExternal)
{
Ajax.request({url:url, onSuccess:renderProcess, onFailure:onFailure})
}
else
{
var src = script.innerHTML;
renderProcess(src)
}
}
catch(e)
{
onFailure()
}

An other way to load a js file in js code

I opened a javaScript file in a javaScript time....
document.write("<script src='newnote.js' type='text/javascript'></script>");
is there an other way to load the js in js code..?
(this file is for loading a popup menu js code , which is loaded after delay by clock js code ... so i want an othe way to loaded it)
When opening a JS file, its code is executed at once - functions are created, code is run, events are set. The only way to 'unload' a Javascript file is to manually undo all the code that has been run as a result of loading the unwanted file: setting all new functions, variables and prototype aditions to undefined (e.g. window.badFunction = undefined, unset all events, remove all new DOM elements..
If you wanted to unload another JS file every time when opening a page, it could in theory be done, but not very easily and if the loaded JS file should change, you would have to update your invalidating file.
What you did isn't like opening a local file in a programming language like C++ or Java. You don't need to close anything.
Is it possible that the script that you are adding to the page (in this case newnote.js) is causing the error you are experiencing?
Instead of the line you used starting with document.write use this instead:
var newnote = document.createElement('script');
newnote.src = "newnote.js";
newnote.type = "text/javascript";
document.documentElement.firstChild.appendChild( newnote );
If you still get your quotes error, then the code inside of newnote.js is messed up.
Don't think this was really what you were asking, but if you used the code I listed above you could then remove this file from your page by calling this:
document.documentElement.firstChild.removeChild( newnote );
One more thought:
If your path to newnote.js is not correct (because it is not in the same directory as the calling page) then the server would return a 404 error page instead of the file. If your browser tried to execute it like javascript, it could throw an error. Try supplying the full URL: http://yoursite.com/js/newnote.js or a root relative one: /js/newnote.js
you are not opening a javascript file, in fact you cannot open any file from local file system, so there is no question of closing. You are inserting a script tag replacing all contents of the document. This would result in fetching newnote.js using the current url with newnote.js replacing anything after last slash.
To include a script you could try this:
var s = document.createElement('script');
s.src = 'newnote.js';
s.type = 'text/javascript';
var head = document.getElementsByTagName('head')[0]
head.appendChild(s);
or like that:
document.write("<script type='text/javascript' src='newnote.js'><\/sc" + "ript>");

Categories

Resources