Add variables to a .js file - javascript

I'm looking for a way to post variables in an external .js file.
Something like:
<script type="text/javascript" src="/js/script-starter.js?var=value"></script>
And then I'd like to call var (and thus, value). Is this possible in any way?
Thank you!

Yes, it is possible. You will have to look for all script tags in the DOM (make sure the DOM is loaded before attempting to look in it) using the document.getElementsByTagName function, loop through the resulting list, find the corresponding script and parse the src property in order to extract the value you are looking for.
Something along the lines of:
var scripts = ​document.getElementsByTagName('script');
​for (var i = 0; i < scripts.length; i++)​ {
var src = scripts[i].src;
// Now that you know the src you could test whether this is the script
// that you are looking for (i.e. does it contain the script-starter.js string)
// and if it does parse it.
}​
As far as the parsing of the src attribute is concerned and extracting the query string values from it you may use the following function.

it could be possible if that script is a serverside script that receives the variable in querystring and returns a javascript code as output

How about declaring the variable before script file loading:
<script type="text/javascript">var myVar = "Value"</script>
<script type="text/javascript" src="/js/script-starter.js"></script>
So you can use this variable in your script. Possibly this is one of the easiest ways.

Why don't you put the variables in a hidden a or p
<a id="myHiddenVar" style="display:none;">variables</a>
Then in your .js you access it with
var obj = document.getElementById("myHiddenVar").innerHTML;
or the jQuery style
var obj = $("#myHiddenVar").text();

function getJSPassedVars(script_name, varName) {
var scripts = $('script'),
res = null;
$.each(scripts, function() {
var src = this.src;
if(src.indexOf(script_name) >= 0) {
varName = varName.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var string = new RegExp("[\\?&]"+ varName +"=([^&#]*)"),
args = string.exec(src);
if(!args.length) {
res = null;
} else {
res = args[1];
}
}
});
return res;
}
console.log(getJSPassedVars('script-starter.js', 'var'));
in my case my app folder structure is like following:
MyApp/
index.html
jquery.js
my.js
above function is within my.js with console.log and include it within index.html.

Related

call and read external JS file - Angular

I have an external (on a server) JS file I am calling and need to read.
This is for Captcha use.
I am having an issue since the TlvJs object is undefined while calling the JS file.
When debugging, I have noticed that the $(document).ready is being executed before the TlvJS was actually declared.
When using the files locally (keeping them in assets folder), first, the TlvJS is being declared and just then the $(document).ready.
How can I make the TlvJS object declared first, even when the file is calling externally?
Please note, I can't control the order of the objects inside this JS file.
$(document).ready(function () {
//select all controls
var elements = document.querySelectorAll('div[tjs-control]');
//iterate thru all found controls
for (var i = 0; i < elements.length; i++) {
var elm = elements[i];
switch ($(elm).attr('js-control')) {
//Captcha control
case "TlvJs.UI.Captcha":
var cap = TlvJs.UI.Captcha($(elm).attr('id'));
var options = $(elm).attr('js-options');
setInstanceProps(options, cap);
cap.url = SetClientProtocol(cap.url);
cap.initCaptcha();
$.prototype.Captcha = cap;
break;
}
}
});
var TlvJs = {
UI: {
Captcha: function (tagId) {
var cap;
cap = Captcha(tagId);
return cap;
},
FileUploader: function (options) {
return FileUploader(options);
}
},
Utils: {
},
Navigation: {
}
};
Currently, I am adding the JS files manually inside a .ts file since when adding the Js files inside the index.html the elm element in the JS file is undefined. That way, the Html page wasn't actually loaded yet.
The first way I have tried (with index.html) which cause the "unknown" elm element:
<script src="http://xxx/Services/CaptchaServicesDistributed/Scripts/TlvJs-Captcha.js"></script>
<script src="http://xxx/Services/CaptchaServicesDistributed/Scripts/TlvBaseJs.js"></script>
The second (and current) way is :
let tlvBaseScript = document.createElement("script");
tlvBaseScript.defer = true;
tlvBaseScript.src = this._configService.getTlvBaseScriptUrl();
tlvBaseScript.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(tlvBaseScript);

Call function from another js file when using iife pattern?

Is it possible to call function that is in one js file and it is made public by usage of iife pattern, in another js file?
For example, this is some validationScript.js file:
var ValidationNamespace = function ()
{
var nameValidation = "";
var testValidation = "";
return{
validateIfNameAlreadyExistsInTable : function(currentNameValues)
{
for(var i=0; i < currentNameValues.length ; i++)
{
if(document.getElementById("tbName").value == currentNameValues[i])
{
var nameVal = "Name already exists in table!";
document.getElementById("nameVal").innerHTML = nameVal;
return false;
}
}
document.getElementById("nameVal").innerHTML = "";
return true;
}
};
}();
And I have another file, lets say script.js
Is there some way to call function validateIfNameAlreadyExistsInTable from some script.js function?
The problem is that it is undefined when I try to call it:
I have index.html where I am referencing both .js files like this:
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="validationScript.js"></script>
Yes, because the IIFE returned an object that exposes the function, and the file saves that object as ValidationNamespace, which is a var declared globally and thus a global variable.
So:
ValidationNamespace.validateIfNameAlreadyExistsInTable(theName);
Re your edit, you probably want to load the scripts in the other order, first validationScript.js then script.js:
<script type="text/javascript" src="validationScript.js"></script>
<script type="text/javascript" src="script.js"></script>
Scripts are loaded and run in the order you give them (unless you use async or defer). So unless your code in script.js is waiting for some other event, it'll run before validationScript.js is loaded.
I think this should work.
ValidationNamespace().validateIfNameAlreadyExistsInTable(theName);

Access variable from another script source

<script src="http://domain.com/source1.js"></script>
<script src="http://domain.com/source2.js"></script>
source1.js
var PICTURE_PATH = "";
var PICTURE_ROOT = base_url+"YOUTAILOR_files/";
var PROGRAM = parseInt("1");
source2.js
if(PROGRAM==3 || PROGRAM==4 || PROGRAM==5)
{
}
I could not access value of program in source2.js..
When you declare var source1Var outside a function you are actually creating a variable on the window object. So you should just be able to access it from source2.js. Just make sure source1.js is before source2.js in the script tags...
If however you're declaring it within a function, it will be private to that function. If you really need to you could set it on window explicitly.
In source1.js
function foo() {
window.source1Var = 3;
}
In source2.js
function bar() {
console.log(source1Var); // this will search window if it cannot find in the local scope.
}
What is the problem you're trying to solve? It is generally better to use some form of dependency injection, event listeners, builder pattern etc. rather than using global variables.
do something like in your first .js
var VAR = {
myvalue: "hai"
};
then call it in second like
alert(VAR.myvalue);
It's easier than you think. If variable is global, you should access it from anywhere.
// source1.js
var colorCodes = {
back : "#fff",
front : "#888",
side : "#369"
};
And in another file:
// source2.js
alert (colorCodes.back); // alerts `#fff`

How to define Global Arrays?

Code example:
<script>
var data = new Array();
data[0] = 'hi';
data[1] = 'bye';
</script>
<script>
alert(data[0]);
</script>
This gives the following error: data is not defined
How do you make something like this work? Especially if the first <script> block is being loaded on the page by ajax, and the second block is working from it. jQuery solution is acceptable.
New is not a keyword.
Use:
var data = new Array();
Or, more succinctly:
var data = [];
After your edit you mention that the first script block is loaded asynchronously. Your code will not work as written. data is a global variable, once it is loaded onto the page. You need to use a callback pattern to properly execute the code.
Since you haven't posted the asynchronous code I am not going to provide a callback sample. Though, a quick solution follows:
var interval = setInterval(function(){
if(data) {
/* ... use data ... */
clearInterval(interval);
}
}, 500);
To create a global variable, just omit 'var' from the statement. When you omit 'var', you're actually creating the variable in the window namespace.
So, zz = 1 is actually window.zz = 1
If you really wanted to, you could explicitly say
window.data = new Array(); //remember that new should be lowercase.
But you can write that faster anyway by saying
data = ['hi','bye'];
alert(data);
If you're using jQuery, perhaps you should try .getScript() rather than using .html();
// in separate file
data[0] = 'hi';
data[1] = 'bye';
// in main file
var data = [];
$.getScript(url).done(function() {
alert(data[0]);
}).fail(function() {
// handle error
});
<script>
data = [];
data[0] = 'hi';
data[1] = 'bye';
</script>
<script>
alert(data[0]);
</script>
use this, remove var makes variable global

call a java script function in a js file from a function of another js file

my problem is that i have two js file (1.js, 2.js), in both has the same functionality , methods(or like a copy of file). now i want to call a function (like _finish() ) from one js(1.js) file to another js file(2.js) file. can anyone give a solution.
Create your own namespace and pull all "public" methods (to your application) in there.
1.js
window.yourspace = window.yourspace || {};
window.yourspace.app = (function() {
var foo = 1;
return {
publicfunction: function() {
alert('hello world');
}
};
}());
2.js
window.yourspace = window.yourspace || {};
if( yourspace )
yourspace.app.publicfunction();
I agree with jAndy. In your case you must use namespaces.
For example, if you have script one defining variable a and then the second script defining it's own variable a, when the 2 scripts are put together, the last script executed by the browser overwrites the a variable :
//script 1
var a = 'script 1 value';
// ...
//script2
var a = 'script 2 value';
// ...
alert(a);
When you execute the above example, you'll see that the second script has redefined your a variable. So, the best way to do this without having name conflicts is using namespaces:
//script 1
script1Namespace.a = 'script 1 value';
// ...
//script2
script2Namespace.a = 'script 2 value';
// ...
alert(script1Namespace.a);
alert(script2Namespace.a);

Categories