Cannot get global variable in another js file - javascript

I currently have this global variable declared in javascript.js which I've imported to my main document.
var globalURL = "test URL";
When I try an alert within the javascript.js file it successfully outputs the value of globalURL.
However when I try to an alert with my current document but calling globalURL I get an error
Uncaught ReferenceError: globalURL is not defined
I'm I doing something wrong here? I followed the example here but still it doesn't work for me. Can I access variables from another file?
UPDATE:
I have included my javascript.js file with my current document, so I don't think the error is there. Otherwise the first alert function within the javascript.js wouldn't have run at all.

In your HTML file, you are probably loading the file that you use globalURL before you load the one that sets globalURL

Open your browser's developer section and there scripts tabs. Observe that both js files are loaded into memory. I believe one of them is not loaded. Global valiarbles in js are available in combined space.

Another possibility is that you might be declaring it from inside of a function somewhere. If you want to declare a global variable from inside a function, try leaving off the var at the beginning. This would look like
globalURL = "test URL";

Related

Retain value of variable between different html files

Fairly new to Javascript.
Imagine I have a Javascript file: Book.js, inside which I just have some global variable: var globalVar = 0;
Imagine I also have two separate html files: A.html and B.html, both of which use above script: e.g. have <script src="src/model/Book.js"></script> inside.
Now, when I opened A.html I could see globalVar was defined. Then I incremented is using console.
Then, when I opened page B.html, I was expecting globalVar to retain its value (since I declared it as global inside Book.js file and B.html also loaded Book.js) but it was undefined.
Is that expected?
Does it mean scope of global variables is inside one html page?
Apparently the second time the Book.js script got loaded, variables declared during previous invocation of Book.js "disappeared".
Is that expected?
Yes
Does it mean scope of global variables is inside one html page?
It is more akin to each page being a new program (and a reload of a page being akin to exiting the program and then running it again).
So it means you must use localStorage or something similar if you want to access variable declared in other page?
Yes. That's why localStorage was created.
Yep, the Javascript is loading in one page and cannot be changed this way, because you are reloading it from your server. Basically, each page is a different process.
However, you can use a lot of workaround like :
LocalStorage : https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
Cookie : https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
And if you use a complex application, you can manage your gobal variable in back

How to obtain location of the code being executed in Nodejs

Trying to create a logger javascript class, that I add as a require() in other javascript files. One of the functions of this logger should be, that it writes to the console which script is currently running.
They way I thought it would execute , was that I have a path.basename(__Filename) function inside my logger, but how would I go around targeting the filename of the script executing the logger script?
There is no way to know which file the script itself is in as the browser loads all the scripts under the DOM while loading the page.
function xyz(){
console.log(arguments.callee.toString().match(/function ([^\(]+)/)[1]);
}
This should give you the name of the function that's being called as long as the function is declared in function xyz(){} format. In this case xyz.

Global variable created inside CrossRider's appAPI.ready() function not available to page?

I am trying to create a Chrome extension using CrossRider and am struggling with how to create a global variable.
My extension is essentially going to dynamically append a few JavaScript files to the page if a button is clicked, and I need it to also create a global variable and set some properties.
I tried the following:
appAPI.ready(function($) {
console.log('inside crossrider extension ready()');
window.foobar = 'barfoo';
return;
});
When I refresh the page, the message inside crossrider extension ready() is printed out to the console, so I know the extension is loaded and working, but when I try executing window.foobar or foobar in the console an error is thrown saying it's undefined.
This is my first time creating an extension, so what am I missing here? Why isn't the global variable I create inside of CrossRider's appAPI.ready() function available outside of it?
I can't find a duplicate target, so I'll explain what's happening.
I don't know the Crossrider terminology, but when a Chrome extension executes code in a page, this is called a Content Script.
However, the code does not execute in the same context as the page itself. It's called an isolated world and means, among other things, that the window object is not shared.
Content scripts execute in a special environment called an isolated world. They have access to the DOM of the page they are injected into, but not to any JavaScript variables or functions created by the page. It looks to each content script as if there is no other JavaScript executing on the page it is running on. The same is true in reverse: JavaScript running on the page cannot call any functions or access any variables defined by content scripts.
So if you want to set a variable accessible to the page, you need to set it in the page context. How? There are many ways, but they all amount to inserting a <script> element into the page.
var script = document.createElement('script');
script.textContent = "window.foobar = 'barfoo';";
(document.head||document.documentElement).appendChild(script);
script.parentNode.removeChild(script);
All of that assumes that you don't control the page in question. If you do, there are other ways of communicating the the page, because DOM is shared. You can, for instance, raise a custom DOM event if the page listens to it.

Get path of lazy loaded JS file from within the file?

If I'm loading a script using something like
document.getElementsByTagName("head")[0].appendChild(scriptElement);
…what code can I put inside of that loaded JS file to get the URL of itself?
In other words: I use dom injection to load http://foo.com/foo.js. From within foo.js, how do I get the URL http://foo.com/foo.js?
If you have included the scriptElement object in your dom, then you should know the "scriptElement.src" - so inside foo.js you should know the source:
alert(scriptElement.src);
I've found a solution that works for me here:
javascript - get node reference to script tag that calls a function
The answer that requires you to throw an error in the loaded file, catch it, and then pass it to the global function in the loading page did the trick. (It doesn't work in IE, but for my current project that is not a concern.)

Stupid js func undefined

I'm writing a Chrome extension, in my background.html page, it is injecting a js file with this command:
chrome.tabs.executeScript(null, {file: "mod.js"});
All of the code from this file is running on the page just fine, except for one function not being defined for an onclick property.
I am changing the innerHTML of Facebook's main page, the div that contains "top news" and "most recent"
I'm inserting this html:
"<a href='#' onclick='thisIsUndefined()'>
<span class='someClass'>
Better feed
</span>
</a>"
And right in the js file that is injected, thisIsUndefined is perfectly stated as:
function thisIsUndefined () {
alert("is it working yet?");
}
I even have another function in the file that I am using, but whenever I click the link that's inserted, the I get an error saying that it's undefined.
Exact error:
Uncaught ReferenceError: thisIsUndefined is not defined
Here's the whole file for reference:
http://texthmu.com/Devin/HMU%20ext/mod.js
Could you recommend any keywords like 'global' or 'var' that could fix the definition?
Scripts on the page and content scripts are isolated. They interact with the same DOM, but not directly with each other's variables. When you add onclick, it's going to look for that function in the site's scripts. The best way to do it would be to use document.createElement and then use onclick or addEventListener to attach your function. If you want to go the innerHTML route, append it to the DOM first, then find it and attach your event.
http://jsfiddle.net/EjYpQ/
You're a bit out of luck on that one due to Chrome's execution model:
Content scripts execute in a special
environment called an isolated world.
They have access to the DOM of the
page they are injected into, but not
to any JavaScript variables or
functions created by the page. It
looks to each content script as if
there is no other JavaScript executing
on the page it is running on. The same
is true in reverse: JavaScript running
on the page cannot call any functions
or access any variables defined by
content scripts.
(emphasis in bold)
Source: http://code.google.com/chrome/extensions/content_scripts.html#execution-environment
This is the best solution I found:
$("#elementID").click(function() {
myFunc();
});

Categories