Send data across two pages using JavaScript - javascript

I am a .NET stack developer and I am not so strong in JavaScript. I want to pass a variable defined in the script tag of one html page and retrieve it in a different page. By the time execution control gets to the second page, the value assigned to the variable has been lost and subsequently testVar is null. I'm trying to achieve something similar to this:
In C# I would define a static global variable to achieve this.
HTML Page 1:
<script>
var someVariable = "Hello Word";
</script>
HTML Page 2:
<script>
var testVar = someVariable;
//Expecting testVar to be assigned with Hello World
</script>

You could store your variable in the global window object.
var someVariable = "Hello Word";
window.stored_value = someVariable;
The window object is global, so just use it in another script.
HTML Page 2:
<script>
var testVar = window.stored_value;
</script>
Please have a look at a similar issue:
Storing a variable in the JavaScript 'window' object is a proper way to use that object?

You'll most likely need to look into the postMessage API, but without knowing more about the two windows and how they are related to each other (was one opened by clicking on a link in the first, for example) it's hard to give you more direction.

Inother to access external javascript in your html file, create a separate .js file e.g script.js and define someVariable in it then add the script to both html files via the script tag as so <script src="script.js"></script>.
In the script.js file add the code:
var someVariable = "Hello Word";

Related

How to invoke JavaScript functions from an external .js file in JavaScript WITHOUT HTML?

I am using iMacros in combination with JavaScript in Firefox. The required scripts are stored on my harddrive. The scripts I am using are not embedded into a website. I am familiar with the procedure of how to make use of several JavaScript files in an HTML context but since I do not have that context in this case, is there some way I can continue?
Example:
script1.js
function Message(message) {
alert(message);
}
script2.js
//Some reference to the file script1.js
var message = "Hello";
Message(message);
In that case I would want to run script2.js and have the alert pop up.
I appreciate your help.
I'm used to apply something like this:
// Some reference to the file script1.js
var extScript = imns.FIO.openNode("D:\\Temp\\script1.js");
extScript = imns.FIO.readTextFile(extScript);
eval.apply(window, [extScript]);
var message = "Hello";
Message(message);

How to access a variable among multiple javascript files

Currently i have 2 html pages and 2 java script pages,say
h1.html,h2.html
j1.js,j2.js
where can i declare a variable so that the variable can be accessible between both of java script and html files
i want to initialize a value to that variable in first java script file and access that value in the second java script file
if you want to access variable values across two html files even after the page loads you can use localStorage in js.
say if you want to set a value for a variable localStorage.setItem("newvariable", 'variablevalue'); and for getting value use this var getValue = localStorage.getItem("newvariable");
EDIT:
for your base question refer those js files one by one
<script src="j1.js"></script>
<script src="j2.js"></script>
you can declare the variable in any javascript file, and just include the file next to the other javascript file forexample.
// for example if you have file1.js like this.
var myvalue = 25;
You can then save this file and include it in your main or other html files for example at the bottom of your html document.
<html>
<body> </body>
<script src='file1.js'></script> // put the javascript file with your variable declaration on top of the other file you want to access the value from.
<script src='file2.js'></script>
</html>
after the above you can then just print the variable in 'file2.js' like this.
// inside file2.js
console.log(myvalue) // which was declared in the 'file1.js'
hope this helps.
You can bring your javascripts in to the <head> of your html then you can refer to the javascript as a function passing values as a parameter and returning data as well.
PS Don't forget to declare the javascript on your form.

Is there a way to send variables to javascript files?

is it possible to do something like this
to send the value id=3 to the js file
<script src="http://site.com/js/loader.js?id=3" ....
otherwise what's the approach to do that?
No, that won't work.
Just set the variables before you load the file:
<script>var id = 3;</script>
<script src="http://site.com/js/loader.js" ....
Since all the scripts share a global namespace, you'll be able to access the id variable from inside your loader.js file.
Of course you should think about the style and implications of using global vars to achieve that. Using a global object that hold these config variables might be a cleaner approach.
If that is just a javascript file, you can just define the variable before load it.
<script>
var id = 3;
</script>
<script src="http://site.com/js/loader.js" ....
It would work, but not if your .js URL is just for a static file. If you wrote server-side code that output JavaScript, then you could output custom JavaScript based on the query string.
This is probably overkill for what you're trying to achieve.
k so this question has pretty much been answered. But there is another approach, which may or may not be suitable for you. If you want to render script conditionally or fetch a certain script for a certain id. You can declare it in a serverside script
http://site.com/js/loader.js.php?id=1
In the loader.js.php
Just use the following line in the beginning
<?
header("Content-type: text/javascript");//To declare it is a javascript file
$id=$_REQUEST['id'];
?>
//Normal js continues after this
//When you need to use the variable, just use
var id=<?=$id?>

How would I pass data to an external script loaded with $.getScript()?

So I'm trying to load a javascript remotely using jquery's $.getScript, but I'm puzzled on how I can pass data to the external script.
I've tried setting variables before the call but they aren't available in the script that gets loaded, and when I try to send/retrieve them using the query string, the remote script tries to read the querystring of the base file that it gets called from, not itself. Is there any other way to do this? Or is it possible to have a javascript file read its own querystring rather than the file it's called from (that's loaded in the browser)?
// editor ini
var editor_ini = { page: current_page, action: 'edit' };
var foo = 'bar';
// load the editor
$.getScript('assets/desktop/desklets/'+launcher.config.editor+'/execute.js', function(){});
In the execute.js file, the editor_ini and foo are both unavailable, I get the same result with:
// load the editor
$.getScript('assets/desktop/desklets/'+launcher.config.editor+'/execute.js', { page: current_page, action: 'edit', foo: 'bar' }, function(){});
because the remote script seems to be getting the query string from the original document rather than the one used when calling the file.
If it matters, I was trying to use the query object plugin for jquery for reading the query string.
global variable declared in inline javascript is accessible in external javascript page loaded using $.getScript().
I bet that your var foo='bar' is inside a function, so not visible in global scope. Try:
window.foo = 'bar'
Truly global variables will be accessible to your script. So, if they aren't, then it's probably because your variables that you think are global actually aren't. You can either move them to the top level scope or set them on the window object like Alexei suggested.
There are other ways to share data.
1) You can put an id on the <script> tag that loads the code and then have the code get the .src value from that tag and get the query string off the script's actual URL. I like this option, but I don't know if you can do it using jQuery.getScript() since I don't think it exposes that as an option.
2) You can have the loading script call a function that you provide and return an object with the desired data from that function.
3) Once the new script is loaded, you can call a setXXX() function in that script to set the state that it needs.
4) You can set information into a cookie that the other script can read.
5) You can encode data into a URL hash value that the other script can read.

How can I have the same javascript variable on the same page?

Our service offers the ability to drop in some javascript on your page and display some tracking data, but I'd like for customers to be able to embed multiple instances of the embed code on the same page.
The problem right now is that I can't include the same variables names on the page.
For instance:
<script type="text/javascript">
var ttp_number = "1Z8E26R80281495993"; // Tracking number
var ttp_key="123456";
(function(){
document.write('<div id="ttp"></div>');
s=document.createElement('script');
s.type="text/javascript";
s.src="http://c.trackthepack.com/j/e?" + Math.random();
setTimeout("document.getElementById('ttp').appendChild(s);",1);
})()
</script>
Then if they wanted to be able to embed that again, I'd have to change all variable names:
<script type="text/javascript">
var ttp_number_001 = "446888240962"; // Tracking number
var ttp_key_001="123456";
(function(){
document.write('<div id="ttp_001"></div>');
s_001=document.createElement('script');
s_001.type="text/javascript";
s_001.src="http://c.trackthepack.com/j/e?" + Math.random();
setTimeout("document.getElementById('ttp_001').appendChild(s_001);",1);
})()
</script>
I'm okay with having them change the contents of the function() block, but the ttp_number and ttp_key need to stay the same variable name.
Right now, when I have multiple embeds on the page, they all inherit the contents of the variables in the last embed code.
So, the ultimate question here...how do I fix that?
Maybe store the ttp_key and ttp_number's in arrays instead?
Why not declare the variables in the function body. Then they're only scoped to that function. You can still set them to different values when you dump the script into the HTML.
I know you mention/imply that the user can edit the function (for some reason) but that just seems like a world of hurt to me, so I'm hoping that that's not actually the case.
Why are you cachebusting with Math.random()? Does the JavaScript at http://c.trackthepack.com/j/e change often? If not, you should let the cache do its job.
But if so, could you make it dynamic enough to inspect the arguments it's called with and use those arguments directly, instead of relaying them via the global window object, so that you load http://c.trackthepack.com/j/e?n=446888240962&k=123456 and it doesn't have to look them up when the script runs?

Categories

Resources