Accessing the location object of an external script from the external script - javascript

Here's an interesting JS q... suppose you have:
host1.html on host1.com which references an external javascript (host2.js) on host2.com. In the host2.js, I'd like to get the location.hostname of the host serving the host2.js, but because host2.js is called inside of host1.html, it returns the location.hostname of host1.
Is there a way to get the location object of the external script within the external script being called?

I think similar questions have been asked before, and the answer was always no, this can't be done.
Workarounds:
Work through the parent document's script elements and, using a counter variable, find out which one we're in (ugh)
Output the current URL into the included script on server side, e.g. in PHP: script_current_url = <?php echo "http://".$_SERVER["HTTP_HOST"]."/".$_SERVER["REQUEST_URI"] (there's a variable for the protocol part too, I just forgot the name)
Set a variable before each <script> tag:
<script type="text/javascript">
script_current_url = "http://www.example.com/include.js";
</script>
<script type="text/javascript" src="http://www.example.com/include.js">
</script>
this is kludgy, but could be simplified by building a JS function that includes the file and sets the right variable automatically.
I like the server-side approach the best, but depending on your platform, it has other implications like having to send all .js resources through a resource-expensive interpreter.

Related

Is it possible to inject an external javascript reference into the host page from a SWF?

I have a SWF advert that needs to call the Facebook API, for which I need the following single-line reference in the host HTML page:
<script type="text/javascript" src="//connect.facebook.net/en_US/all.js"></script>
Since I am dealing with an advert, I don't have control over the host page. I understand I can inject functions into a page (there's a good reference for this here: http://www.actionscript.org/resources/articles/745/4/JavaScript-and-VBScript-Injection-in-ActionScript-3/Page1.html), but I haven't found a way to add a reference to an externally-hosted script.
Does anybody know if this can be done, and if so, how?
Just add a SCRIPT tag dynamically to the document. You can do that by running a anonymous function through ExternalInterface:
var js:Array = [
'var script = document.createElement("SCRIPT")',
'script.src = "http://connect.facebook.net/en_US/all.js"',
'var head = document.getElementsByTagName("HEAD")[0]',
'head.appendChild(script)'
];
ExternalInterface.call('(function(){' + js.join(';') + '})()');

Inject local .js file into a webpage?

I'd like to inject a couple of local .js files into a webpage. I just mean client side, as in within my browser, I don't need anybody else accessing the page to be able to see it. I just need to take a .js file, and then make it so it's as if that file had been included in the page's html via a <script> tag all along.
It's okay if it takes a second after the page has loaded for the stuff in the local files to be available.
It's okay if I have to be at the computer to do this "by hand" with a console or something.
I've been trying to do this for two days, I've tried Greasemonkey, I've tried manually loading files using a JavaScript console. It amazes me that there isn't (apparently) an established way to do this, it seems like such a simple thing to want to do. I guess simple isn't the same thing as common, though.
If it helps, the reason why I want to do this is to run a chatbot on a JS-based chat client. Some of the bot's code is mixed into the pre-existing chat code -- for that, I have Fiddler intercepting requests to .../chat.js and replacing it with a local file. But I have two .js files which are "independant" of anything on the page itself. There aren't any .js files requested by the page that I can substitute them for, so I can't use Fiddler.
Since your already using a fiddler script, you can do something like this in the OnBeforeResponse(oSession: Session) function
if ( oSession.oResponse.headers.ExistsAndContains("Content-Type", "html") &&
oSession.hostname.Contains("MY.TargetSite.com") ) {
oSession.oResponse.headers.Add("DEBUG1_WE_EDITED_THIS", "HERE");
// Remove any compression or chunking
oSession.utilDecodeResponse();
var oBody = System.Text.Encoding.UTF8.GetString(oSession.responseBodyBytes);
// Find the end of the HEAD script, so you can inject script block there.
var oRegEx = oRegEx = /(<\/head>)/gi
// replace the head-close tag with new-script + head-close
oBody = oBody.replace(oRegEx, "<script type='text/javascript'>console.log('We injected it');</script></head>");
// Set the response body to the changed body string
oSession.utilSetResponseBody(oBody);
}
Working example for www.html5rocks.com :
if ( oSession.oResponse.headers.ExistsAndContains("Content-Type", "html") &&
oSession.hostname.Contains("html5rocks") ) { //goto html5rocks.com
oSession.oResponse.headers.Add("DEBUG1_WE_EDITED_THIS", "HERE");
oSession.utilDecodeResponse();
var oBody = System.Text.Encoding.UTF8.GetString(oSession.responseBodyBytes);
var oRegEx = oRegEx = /(<\/head>)/gi
oBody = oBody.replace(oRegEx, "<script type='text/javascript'>alert('We injected it')</script></head>");
oSession.utilSetResponseBody(oBody);
}
Note, you have to turn streaming off in fiddler : http://www.fiddler2.com/fiddler/help/streaming.asp and I assume you would need to decode HTTPS : http://www.fiddler2.com/fiddler/help/httpsdecryption.asp
I have been using fiddler script less and less, in favor of fiddler .Net Extensions - http://fiddler2.com/fiddler/dev/IFiddlerExtension.asp
If you are using Chrome then check out dotjs.
It will do exactly what you want!
How about just using jquery's jQuery.getScript() method?
http://api.jquery.com/jQuery.getScript/
save the normal html pages to the file system, add the js files manually by hand, and then use fiddler to intercept those calls so you get your version of the html file

Is it possible to use a single javascript tag for loading an external js file and calling its function?

I am writing a third party javascript (my.js) that can be inserted in a HTML page using script tag. I want to achieve the following:
my.js gets loaded (which has a function myFunc(params))
myFunc() gets called with appropriate params (parameters can change)
putting my.js script in head is not an option
What is the best approach that I can use?
The problem is that you can't really pass parameters w/ just 1 script tag pointing to an external file, so you would have to get them from some element in the DOM:
The html:
<html>
<body>
<script src="my.js"></script>
<input id="params" type="hidden" value="'param1', 'param2', 'param3'" />
<div id="result"></div>
</body>
</html>
The javascript:
function myfunc() {
var doc = document,
params = doc.getElementById("params").value.split(","); // make an array of params
doc.getElementById("result").innerHTML = params.toString();
}
window.onload = myfunc;
Honestly though, this is a kludge. As mentioned before by Felix, you should probably just use 2 script tags -- One to get the external js file and one to call the function with the parameters you need.
You can pass parameters in via the query string and parse them out dynamically.
For example, your script tag becomes:
<script src="my.js?foo=bar"></script>
You can then get the value of the URL using:
var scripts = document.getElementsByTagName('script');
var url = scripts[ scripts.length - 1 ].getAttribute('src');
Because of the order JS is loaded by the browser, the last script on the page (while your script is executing during load) should always be your script.
Then you parse the query string. There are a bunch of questions on Stack Overflow dealing with that. Ex:
Parse query string in JavaScript

javascript get Value

code :
<script type="text/javascript" src="http://127.0.0.1/Test.js#username=stackoverflow">
</script>
iwant to know ,how to get the username in Test.js
file
Test.js :
var username = ??
///////////// #username=stackoverflow
thanks advance
If you are trying to do all this on the client side, it's much better to use:
<script type="text/javascript">//<![CDATA[
var username = "stackoverflow";
//]]></script>
<script type="text/javascript" src="http://127.0.0.1/Test.js"></script>
That way, you don't need to tackle the issue of reading the src attribute of the script tag somehow.
The query portion of the URL is invalid. It should be:
http://127.0.0.1/Test.js?username=stackoverflow
The # is treated as a named anchor.
The gup function isn't good because the parameter is on the script tag, not the HTML output page.
The location object (location.href, location.search...) refers to the HTML page where the script included.
There are 2 other options:
Use this
Use #idealmachine answer. You can wrap the global variable with simple object in order to avoid conflict with other global JS variables

Can I get the location of where a JavaScript library is loaded from, from within the script?

Lets say I have a page with this code on it on www.foo.com:
<script src="http://www.bar.com/script.js" />
Can I write code from within script.js that can check that it was served from bar.com? Obviously document.location.href would give me foo.com.
Thanks!
var scripts = document.getElementsByTagName("script");
give you a collection of all the scripts in the page
After this you can read their src property to find your target (I hope you know how the script is called)
for (var i=0, limit=scripts.lenght; i< limit; i++) {
if (scripts[i].src.substr(<calculate your offset>) == scriptName) {
// Have you found your script, extract your data
}
}
The only way to find out the location of a non-worker script is the non-standard error.fileName, which is only supported by Firefox and Opera:
var loc = (new Error).fileName;
If the script is a worker thread (which of course it isn't), then you could just use the location object.
If it's really important, you could work around it by defining a string containing the script URL in front of each script tag:
<script type="text/javascript">SCRIPT_URL = "http://www.bar.com/script.js"</script>
<script src="http://www.bar.com/script.js" />
Inside the script file you can then access the URL
alert("my URL is "+SCRIPT_URL);
Not too elegant but should work.
You could also, if you have a server-side language like PHP and don't mind sending JS files through the interpreter (Big performance caveat!), do something like this within the JS file:
<script type="text/javascript">var my_url = "<? echo $_SERVER["REQUEST_URI"]; ?>"</script>
but that should really, really be the last resort.
You can wrap your script in a condition, kind of like an adult diaper, if you insist.
if(top.location.host==='www.bar.com'){
//the whole script goes here
}
else alert('Nyah Nyah Nyah!')

Categories