How to declare a function in the scope of the browser? - javascript

a function can be declared in the scope of the window-object that is accessible in that particular tab of the browser. The syntax is as follows:
window.f1=function(){
//statements...
}
But is there a way to declare the function in the scope of the browser so that the function is accessible through any tab open in the browser. I want a syntax equivalent to the following
browser.f1=function(){//browser is what I want.
//statements...
}
Can anyone suggest me a possible way?

Thanx to the comments received on my question, I achieved it using localStorege. A quite fair reference is http://dev.w3.org/.
code
<script>
if(!localStorage.a)
localStorage.a=10;
</script>
If this script is included in a webpage of a particular domain(say www.example.com). Then whenever that page or any other page belonging to that doman is opened in the previously used browser, you can access it as localStorage.a which will be 10 in this case until and unless you explicitly delete localStorage.a.
This is probably the simplest and shortest and hence the best solution to my problem. Thanx to everyone for providing the relevant info.

Related

TypeScript doesn't have window.eval()

In JavaScript I can do:
window.eval(userInput)
in a client-side .js file without any issue.
But in TypeScript, window.eval() does not exist. I get the error:
property eval does not exist on type window
How can I get around this issue?
The reason I want to use eval() is to execute some user created code. The eval call must be done on a global scope because the user code relies on some other code that I have already previously loaded with <script> tags.
There are a couple of ways to do this.
Use type assertion (Type unsafe, but quick and easy):
(window as any).eval("1 + 1");
Or you can modify the window declaration as described in this issue (Type safe)

Can I resolve this "Cannot read property 'xxxx' of undefined" issue by using keyword 'defer'?

In my web app I inject some user specific data into the html page.
It looks like this in the page source
<body>
<script>
var userData = {};
window.GLOBAL = {
userData: userData
};
userData.user = {'user_hash': 12478999584505 };
</script>
<script src="/static/scripts/myapp.js"> </script>
Inside myapp.js I retrieve the user_hash and call an initialisation function:
init(window.userData.user.user_hash);
A few users experience this problem spuriously:
Cannot read property 'user_hash' of undefined
It turns out it is very hard for me to pinpoint the exact cause of the problem. This error never happen to me in either production or development environment. There is also no error on the server side that indicates the user_hash generation has failed. I have tried to reproduce this error by throttling network speed in Chrome via Dev Console etc but I haven't been able to trigger this error yet.
On the user side, the platforms vary from mobile devices (could be running the latest version of iOS or andriod) to desktop, and different browsers (chrome, firefox or safari). My point is there is no clear pattern I can pin it down to a particular platform or brower version.
I speculate that the exception happens if /static/scripts/myapp.js is loaded and executed before window.GLOBAL is properly initialised, this exception will be fired.
I am thinking of adding defer keyword to the myapp.js script tag, based on this answer.
My questions are:
1) Is there any issue with my current HTML markup? (the two script tags)
2) My hypothesis is basically that these two script tags may have some racing condition between them. Does it stand?
3) Can adding defer attribute to the second script tag potentially fix this issue if answer to question 2 is yes?
4) If answer to question 3 is no, what else I can try?
1) Is there any issue with my current HTML markup? (the two script tags)
No there is no issue with HTML markup.
2) My hypothesis is basically that these two script tags may have some racing condition between them. Does it stand?
I did not get this question perfectly. Probably you should show your myapp code here
3) Can be adding defer attribute to the second script tag potentially fix this issue if answer to question 2 is yes?
No. JavaScript is always synchronous and single-threaded. If you're executing a JavaScript block of code on a page then no other JavaScript on that page will currently be executed. JavaScript is only asynchronous in the sense that it can make, for example, Ajax calls. and Defer instructs the contents of the script tag to not execute until the page has loaded.
4) If the answer to question 3 is no, what else I can try?
You don't require to use GLOBAL here because when you initialize variable with var on top of the script then it may automatically consider in a global scope. JavaScript has two scopes: global and local. A variable that is declared outside a function definition is a global variable, and its value is accessible and modifiable throughout your program. A variable that is declared inside a function definition is local, and second thing window object represents. the browser's window. All global JavaScript objects, functions, and variables automatically become members of the window object.
Here following code may fulfil your requirement
var userData = {
userData: userData
};
userData.user = {'user_hash': 12478999584505 };
console.log(userData.user.user_hash);
Here is also link of working fiddle: https://jsfiddle.net/dipakchavda2912/eohb0npr/

how to get requestscope variable in external javascript

I have some problem regarding request scope variables in spring application. Problem is I have an Object "xyz" which was added to reference data map in SimpleFormController. Now I want to get this object(xyz) from java script. This is done in internal javascript as '${xyz}', but I need to get this from external javascript file. please any one help me out. I know external java script file not come under request scope, But is there any possible solution?
thanks in advance,
The answer is, declare the script variable at global level. Now that variable can have the scope to external scripts files also.

Can I sandbox 3rd party JavaScript to protect the global namespace?

At work I have to deal with a lot of (sometimes awful) JavaScript that vendors expect us to drop into our websites. Some of them add arbitrary, un-namespaced, names to the global scope. I've been toying with different ideas about sandboxing these programs so they don't have direct access to the global scope, but I haven't been able to think of anything that might actually work. (I thought of evalling the fetched code, but I'm convinced that's a bad idea.)
What solutions are there to keep the global scope clean while still using arbitrary 3rd party JavaScript?
Edit: #kirilloid's comment tells me I haven't been clear about how this code is delivered. I'm not usually given code to put into our website. Most of the time, I'm just given a URL and asked to create a script tag that points to it.
Your options are pretty limited. If the code is presented to you in the form of a <script> tag you can't modify, you can stop trying now.
If you can modify the script, you can wrap the code in a closure; this will stop any variables they declare with var being published in the global scope (but you'll still get problems with implicit globals).
(function () {
var aGlobalVariableThatUsedToCauseACollision = 4; // no longer collides!
anotherGlobalVariableThatUsedToCauseACollision = 4; // Mmmmm.
}());
Probably an infeasible option; you could use "use strict" which prevents them using implicit globals, but if the code is as awful as it seems, this won't help you.
An additional change (and prehaps the best) you could make could be to wrap your own code in a closure, and keep local copies of the important window properties (undefined) etc in there; this way you prevent other scripts affecting yours (this is what libraries such as jQuery do).
(function (jQuery, $, undefined) {
alert(undefined == 4); // false!
}(jQuery, $));
undefined = 4;

Get a parameter value in JavaScript

In Cognos 8.4, I have a prompt, "NAME", and its parameter p_name.
How do I get that parameter through JavaScript?
<script>
alert(p_name)
</script>
shows a JavaScript error. Why?
Is my approach correct?
Maybe the reference for the object will be missing, and you have to keep up with the scope of the variables or the parameters. You can use the "Developer Tools" in Internet Explorer 8 by pressing "f12". There in the right hand side pan you can choose the tab "console" to find where you went wrong or you can choose the tab "locals" to find whether the parameter has any values in the scope where you are calling it.
I don't know Cognos, but your problem is that you are calling a variable that is local to an object in the global scope. You have to do whatEverTheObjectIsCalled.p_name (probably). An easy way to find out exactly what you are looking for is to fire up the web page in Chrome and console.log(theObject) and browse through the internals of the object until you find the attribute you want.

Categories

Resources