$_GET inside javascript file? - javascript

For example, I have an script like this: <script src="myjs.js?lol=asd"></script>.
Is there anyway to get the lol inside the js file to alert it, for example, like we can do in PHP? Like:
var lol = $_GET['lol'];
alert(lol);

Use the code from How may I reference the script tag that loaded the currently-executing script? to get a reference to the script tag:
var scripts = document.getElementsByTagName('script');
var thisScriptTag = scripts[scripts.length - 1];
Then you can use thisScriptTag.src to access its src attribute and parse it to get the variable you are looking for

You can't do this with javascript.

Related

Jquery append if location finish with W12345

I need to do a conditional append here is the example url
www.google.com/default.asp/W12345
I want to append a JS file if the url has W and a random string of numbers after it.
How can i achieve this?
Try something like this:
<script>
if (/default\.asp\/W[\d\w]*$/.test(location.href)) {
document.write("<script src='/path/to/your/js/file.js'>");
}
</script>
Insert that code anywhere on the page, typically either in the head, either at the very end of the document.
Use the below snippet on dom-loaded. Here I'm making use of regular expression if it ends with url /wSomeString or /WsomeOtherString.
if(/.+\/w.+$/i.test(window.location.href)) {
var scriptDom = document.createElement("script");
scriptDom.type = "application/javascript";
scriptDom.src = "url/to/js"; //update JS url here.
document.body.appendChild(scriptDom);
}

Can JavaScript access it's own source url?

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

How to find if a JavaScript code is running on it's own domain?

I work on an analytics website and I want to put an analyzer code specific for each website. Is it possible to check if a user uses his own JavaScript code?
Is it necessary and enough to put a customer code in each JavaScript and check it with domain name to be sure about this? Or do I need something like session or so?
You can access the src attribute of the script tags:
// returns all script tags
var all_script_tags = document.getElementsByTagName("script");
// returns the src attribute of the first script
var src_script = all_script_tags[0].src; // tag

pass a variable from js to jquery

wondering how I can pass a variable from load js like:
<script type="text/javascript" src="script.js?myVar=myValue"></script>
and use and pass to script.js itself?
I Know about declare variable before, but I'm looking for url way.
Thanks in advance.
The javascript wont have access to that value. The server would have to look for that and insert that value into the rendered javascript on your behalf.
Usually though, the pattern is more like this:
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript">
ObjFromScript.myVar = 'myValue';
ObjFromScript.doStuff();
</script>
You'd have to locate the <script> tag in the document and extract the arguments. A prominent example of a site using this is facebook with the #xfbml=1 hashtag.
However, the proper/nice way is not putting any code but functions in script.js and then call someFunction(myValue);.
You could do it on the client or the server. On the client, get hold of the script element and parse the src attribute.
<script id="myScript" src="script.js?myVar=foo"></script>
<script>
var s = document.getElementById('myScript');
s.src; // parse it and extract myVar
</script>
On the server, setup routes so that script.js goes to some handler written in a server-side language like PHP. In that case you could be outputting script.js dynamically. Here's an example in PHP.
script.js => script.php
<?php
header('Content-Type: application/javascript');
$myVar = $_GET['myVar'];
?>
// optionally expose myVar inside JavaScript
var myVar = <?php json_encode($myVar) ?>;
// regular JavaScript
alert(myVar);
var x = 10;
You could use document.currentScript, but it isn't widely supported.
var matches = document.currentScript.src.match(/\?myVar=([^&]+)/),
myVarParam = matches && matches[1];
Alternatively, you could try getting the script element with the matching URL and parse out the GET param.
var scriptPath = 'path/to/this/script.js',
matches = $('script[src^="' + scriptPath + '"]').attr('src').match(/\?myVar=([^&]+)/),
myVarParam = matches && matches[1];

Finding javascript's origin

Is it possible from a Javascript code to find out "where" it came from?
I needed this to provide scripts that could run folder-agnostic, e.g.:
http://web1/service-a/script.js
http://web2/some-folder/service-b/script.js
And they're linked in:
http://web1/page1.html
http://web2/page2.html
The file script.js is identical in both locations but I would like them to be able to find out where it originates from so it can call the right web service methods (script.js from service-a should call service-a.method while script.js that is served from service-b should call service-b.method)
Is there a way to find out where script.js came from without using any server-side code?
Well, it's kind of a hack, you could grab all the <script> tags in the document, look at which one has the file name of the file, and do the logic from there.
document.getElementsByTagName('script'); is pretty much all you need. The rest is basic JS.
Even more interesting than looping through all of the returned elements (although that's probably safest), is that we can simply only look at the last element returned by the call above, as Javascript guarantees that must be the <script> tag we're in at the time of it being parsed (with the exception of deferred scripts). So this code:
var all_scripts = document.getElementsByTagName('script');
var current_script = scripts[all_scripts.length-1];
alert(current_script.src);
Will alert the source of the script tag used to include the current Javascript file.
You can analyze source of the html where script.js is included for tag and retrieve path of the script.js from there. Include next function in script.js and use it to retrieve the path.
function getPath() {
var path = null;
var scriptTags = document.getElementsByTagName("script");
for (var i = 0; i < scriptTags.length; i++) {
var scriptTagSrc = scriptTags.item(i).src;
if (scriptTagSrc && scriptTagSrc.indexOf("script.js") !== -1) {
path = scriptTagSrc;
break;
}
}
return path;
}

Categories

Resources