Dynamically accessing changing variable from external .js file - javascript

I'm very new to javascript (c++ normally) and I think this question should be quite basic for you all.
I have a script that gets a variable defined in an external .js file and displays it using an alert.
The code in the .html file looks like this.
<html>
<head>
<title></title>
<script>
function addScript(url){
var extScript = document.createElement('script');
extScript.type = 'text/javascript';
extScript.src = url;
extScript.id = 'extScript'
//If there is already a script with the ID 'extScript'
//get rid of it
var headList = document.getElementsByTagName('head');
var scriptList = headList[0].getElementsByTagName('script');
for(var i = 0; i < scriptList.length; i++)
{
if(scriptList[i].id =='extScript')
{
document.getElementsByTagName('head')[0].removeChild(scriptList[i]);
}
}
document.getElementsByTagName('head')[0].appendChild(extScript);
}
function newNewChangeMode()
{
addScript("C:/Users/Suzaku/Documents/Javascript/controller.js");
alert("Neo controllerMode variable is reading " + controllerMode);
}
</script>
</head>
<body>
Get externally defined mode
</body>
</html>
And the file "controller.js" looks like this.
var controllerMode = 1111;
(that's it!)
When I click the link "get externally defined mode", my javascript runs and the alert is displayed correctly. Displaying "Neo controllerMode variable is reading 1111".
However, if I change the variable controllerMode's definition (in controller.js) to
var controllerMode = 2222;
,hit save, and click the the button again (without refreshing), it still alerts "Neo controllerMode variable is reading 1111". Whereas it SHOULD say "Neo controllerMode variable is reading 2222".
It would seem that this script is not being added dynamically. I need to be able to change this variable without having to refresh the .html.
Thanks in advance,
Guy

It sounds like your browser is only retrieving the cached javascript file. Make sure you go directly to your updated javascript file (controller.js) and hit F5 to ENSURE that you are loading a new version, not the cached one. Otherwise your browser will keep plugging the old, cached script (which has 1111 defined) into your script. Common problem!

Related

WPF WebBrowser.InvokeScript() Keeps Loading Old Script

I have a very simple JavaScript file named as MyJava.htm as shown below:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
function ShowMe(message)
{
var n = message.length;
var s = a.toString();
alert("total length = " + s);
}
</script>
</head>
<body style='background-color:transparent'>
<P>Empty</P>
</body>
</html>
As you can see, there is an error in the code ('a' is undefined). I saved the file into my local machine's web server folder, which is c:\inetpub\wwwroot.
When I first run it using WPF WebBrowser control (this) as follows:
JavascriptInterface jint = new JavascriptInterface(mainWindow);
this.myBrowser.ObjectForScripting = jint;
this.myBrowser.Source = new Uri( #"http://127.0.0.1/myJava.htm");
this.myBrowser.InvokeScript("ShowMe", "Hello");
where mainWindow is a dialog. I'll get the error message saying 'a' is undefined.
Then, I went into the file MyJava.htm and corrected it (replacing variable 'a' with 'n'); saved the file; reran the WPF application.
I still get the 'a' is undefined error.
If I rename the file and change the URL accordingly, then everything works.
Apparently, the old script was being loaded even I've altered the content of the file.
How do I resolve this? How can I tell WPF (or whoever) to load the new contents from the URL?

Loading a JavaScript file dynamically

I was asked to add this code to my pitch pages by the vendor I sell through:
<script>
(function() {
var p = '/?vendor=2knowmysel&time=' + new Date().getTime();
var cb = document.createElement('script'); cb.type = 'text/javascript';
cb.src = '//header.clickbank.net' + p;
document.getElementsByTagName('head')[0].appendChild(cb);
})();
</script>
The code should let the page load within a header that has a red logo by clickbank. When I added the code in the head section nothing happened.
Next I tried to isolate the problem by posting on a blank html page (away from drupal) which is http://www.2knowmyself.com/testpage.htm.
But the frame doesn't show up.
What's wrong in here? Given clickbank claim the code is perfect.
Here's what your code does:
<script>
// the following line creates an anonymous immediately-invoked function
(function() {
// this will return a string named 'p', which contains the vendors ID and current time
var p = '/?vendor=2knowmysel&time=' + new Date().getTime();
// this creates a new 'script' tag for HTML, name it 'cb', and tells the code it's for JavaScript
var cb = document.createElement('script'); cb.type = 'text/javascript';
// this will take a url with the address and the query string, which you named 'p' earlier, and set it as the source for 'cb'
cb.src = '//header.clickbank.net' + p;
// now you'll insert 'cb' to the HTML, so it'll load the JavaScript file into it
document.getElementsByTagName('head')[0].appendChild(cb);
// the function won't run automatically upon declaration, so you use parenthesis to tell it to run
})();
</script>
Summing it up, it bassically sends the vendor's ID and current time to the given server, and expects a JavaScript file in return from it; it'll then load this file into your HTML document.
Currently, it seems not to be working because this server is getting the information from your page but not sending the JavaScript file back to it. When they adjust it to answer with the right file, you'll see it run accordingly.
EDIT: (to answer your Final Question)
Up to this point, I can see that their server isn't sending the expected JS file back at your page, so it doesn't work. If you want to check this by yourself, please use a JS debugger or a network monitor in your browser (most of the modern webbrowsers come with these built-in, try pressing F12 then reloading the page).
If you want to check whether iframes work on your server, you may contact its administrator or try to embed an iframe in the page yourself. Paste the following code into the document. If you see SO homepage, it works. Otherwise, it'll show nothing. If you see Your browser does not support iframes., then you might have to update your web browser and check it again.
<iframe src="http://stackoverflow.com" width="300" height="300">
<p>Your browser does not support iframes.</p>
</iframe>

How do I rotate an ad on a page loading the list of ads from an external file using JavaScript?

I'm trying to load a variable from a file using javascript. I've found some examples but I can't seem to make it work and could really use some help on getting my syntax right.
Basically, I want to load a random ad image on a page, but I would like the list of ads to be pulled from a file. Currently I'm loading the images using the following script which I found on the internet:
<script type="text/javascript">
var picPaths = [
'/images/ad-1.jpg',
'/images/ad-2.jpg',
'/images/ad-3.jpg',
'/images/ad-4.jpg'
]
var oPics = [];
for(i=0; i < picPaths.length; i++){
oPics[i] = new Image();
oPics[i].src = picPaths[i];
}
curPic = Math.floor(Math.random()*oPics.length);
window.onload=function(){
document.getElementById('imgRotator').src = oPics[curPic].src;
}
</script>
I have been trying to get the picPath variable value to load from a file (instead of stating it in the code). I found some code here on stackoverflow and tried adjusted it to the following:
var picPaths = new XMLHttpRequest();
picPaths.open('GET', '/images/liveimages.inc');
picPaths.send();
I also created the file /images/liveimages.inc which containts the following:
'/images/ad-1.jpg',
'/images/ad-2.jpg',
'/images/ad-3.jpg',
'/images/ad-4.jpg'
But, alas, it’s not working and I’m not programmer enough to fix it. :-( I'm thinking my syntax is off but my code could be off too since I am not a JavaScript guy.
Any help would be appreciated and thanks for taking the time to read (and respond) to my question! :-D
If you store the data file as JSON you can use AJAX/XMLHTTPRequest to fetch it, and JSON.parse (available in all modern browsers) to read it.
An easier way perhaps is just to have a script that contains just the data, like:
var picPaths = [
'/images/ad-1.jpg',
'/images/ad-2.jpg',
'/images/ad-3.jpg',
'/images/ad-4.jpg'
];
And then include your scripts in the correct order:
<script type="text/javascript" src="picpaths.js"></script>
<script type="text/javascript" src="ad_script.js"></script>
ad_script.js will be able to access picPaths.
You could have some server-side script generate picpaths.js for you, for instance by looking at the contents of a folder or a database and pulling the ad info from that.

How to get the uri of the .js file itself

is there a method in JavaScript by which I can find out the path/uri of the executing script.
For example:
index.html includes a JavaScript file stuff.js and since stuff.js file depends on ./commons.js, it wants to include it too in the page. Problem is that stuff.js only knows the relative path of ./commons.js from itself and has no clue of full url/path.
index.html includes stuff.js file as <script src="http://example.net/js/stuff.js?key=value" /> and stuff.js file wants to read the value of key. How to?
UPDATE: Is there any standard method to do this? Even in draft status? (Which I can figure out by answers, that answer is "no". Thanks to all for answering).
This should give you the full path to the current script (might not work if loaded on request etc.)
var scripts = document.getElementsByTagName("script");
var thisScript = scripts[scripts.length-1];
var thisScriptsSrc = thisScript.src;
If your script knows that it's called "stuff.js", then it can look at all the script tags in the DOM.
var scripts = document.getElementsByTagName('script');
and then it can look at the "src" attributes for its name. Kind-of a hack, however, and to me it seems like something you should really work out server-side.
script.aculo.us (source) solves a similar problem. here is the relevant code
var js = /scriptaculous\.js(\?.*)?$/;
$$('script[src]').findAll(function(s) {
return s.src.match(js);
}).each(function(s) {
var path = s.src.replace(js, ''),
includes = s.src.match(/\?.*load=([a-z,]*)/);
(includes ? includes[1] : 'builder,effects,dragdrop,controls,slider,sound').split(',').each(
function(include) { Scriptaculous.require(path+include+'.js') });
});
(some parts of this like .each require prototype)

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