Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing javascript arguments via script src attribute [duplicate]

Tags:

javascript

If i have a javascript src like

<script src="http://domain.com/js/script.js"> 

Could i add some more values to the end of it

<script src="http://domain.com/js/script.js?state=1"> 

And get state inside that javascript ??

This idea came from a situation that i have to get client resolution and save it to a session but i can not take it by php , so i have to get it by javascript, but i dont want to show the script nuded from the source code

I think it is possible because i saw many of sources do have link like this!

like image 209
Tin Nguyen Avatar asked Jul 08 '13 16:07

Tin Nguyen


People also ask

How do I pass a variable from one script to another in JavaScript?

There are two ways to pass variables between web pages. The first method is to use sessionStorage, or localStorage. The second method is to use a query string with the URL.

How do you pass a variable to a script in HTML?

There are three ways to display JavaScript variable values in HTML pages: Display the variable using document. write() method. Display the variable to an HTML element content using innerHTML property.

What is defer script?

The defer attribute is a boolean attribute. If the defer attribute is set, it specifies that the script is downloaded in parallel to parsing the page, and executed after the page has finished parsing. Note: The defer attribute is only for external scripts (should only be used if the src attribute is present).


1 Answers

just in case someone wants the actual answer to the actual question instead of resorting to global variables and two script tags:

<script src="http://example.com/js/script.js?state=1"></script>

inside script.js:

(function(){
  var myTags = document.getElementsByTagName("script");
  var src = myTags[myTags.length-1].src;
  var state = unescape(src).split("state=")[1].split("&")[0];
  alert(state);
}());

if you need to pass a lot of stuff, use a common queryString parser to turn the script's queryString into an object.

like image 164
dandavis Avatar answered Sep 28 '22 04:09

dandavis