global variable in javascript to get Geolocation - javascript

i am using the following code to access the geolocation of the blackberry device. its working and showing the desire result. but i want to access the window.GlobalVar outside the body of this function. how can i access it? please help.
navigator.geolocation.getCurrentPosition(function(position) {
var gps = (position.coords.latitude+position.coords.longitude);
window.GlobalVar = gps;
alert (window.GlobalVar);
});
Best regards,

window.GlobalVar will be accessible outside of your function.
What's probably going wrong here is that you're trying to access it before it has been set, seeing as it is being set in a callback function.
getCurrentPosition prompts the user for coordinates, but it is not a blocking call, i.e. it does not simply halt all code execution and wait for the user to make a decision.
This means that you do not set window.GlobalVar during page load, you request it during page load, and you set it whenever the user decides to. So no matter where you call getCurrentPosition you cannot be sure that at a given point, window.GlobalVar will be set.
If you want to be sure that window.GlobalVar is set in the script you're running, you need to make sure that you're running the script after the variable has been set.
navigator.geolocation.getCurrentPosition(function(position) {
var gps = (position.coords.latitude+position.coords.longitude);
window.GlobalVar = gps;
continueSomeProcess();
});
function continueSomeProcess() {
// this code will be able to access window.GlobalVar
}

Calling window.gps after setting window.gps = gps should be enough as it has a global scope since you attached it to window. Take care of the fact that JS is asynchronous, ie gps might not be defined when you call it.

Related

How can I console.log to parent window?

I've got a function that essentially refreshes a table, which works ok, but some of the JS functions don't run. To debug I'm trying to pass data between a popup and it's parent window. Currently I have this function:
$.fn.runFncs = function(isParent)
{
if (isParent == 1) {
window.opener.$.fn.compareDates();
window.opener.$.fn.addStatusIcon();
window.opener.$.fn.iconTooltips(1);
window.opener.$.fn.iconTooltips(2);
window.opener.console.log('test');
} else {
$.fn.compareDates();
$.fn.addStatusIcon();
$.fn.iconTooltips(1);
$.fn.iconTooltips(2);
}
};
and this gets run on an ajax success.
When I hit the button for the ajax, I get my success message etc. but no console.log in my parent window. I've been able to access the parent window before using window.opener and it seems to run ok, just not this time for some reason.
I tried research but either my query was too specific or it was simple "what is console.log" questions so a little stuck here.
Is there an alternative way I can console.log to the parent window? Maybe a document function I'm unaware of?
Thanks! :)
function log(message){
console.log(message);
}
Put that function in your parent window and call it like so. You basically need to provide a wrapper function that you can access
window.opener.log("Hi");
You cannot access directly from one window/tab to anothers's console object, but you can send messages from one window to another. The parent window would get that messages and then it would write it on the console. See this Q&A for more details:
I tried out in recent (2018 aug) Firefox, Chrome and Opera and IE11 too and window.opener.console.log works perfectly in all of them. So I think the problem were somewhere else in your code.
You could even do child.console = console in the parent window and keep console.log, but most of the browsers clear that variable between page loads, and there is no way to set it again right after the document was created, but before the scripts are executed. You can add window.console = window.opener.console to the head of the child page if you can edit that. That should do the trick too.

How can I execute a JavaScript function on the first page load?

I am wondering if there is a way to execute a JavaScript function once only on the first ever page load and then not execute on any subsequent reloads.
Is there a way I can go about doing this?
The code below will execute once the onload event fires. The statement checks if the onetime function has NOT been executed before by making use of a flag (hasCodeRunBefore), which is then stored in localStorage.
window.onload = function () {
if (localStorage.getItem("hasCodeRunBefore") === null) {
/** Your code here. **/
localStorage.setItem("hasCodeRunBefore", true);
}
}
Note: If the user clears their browsers' localStorage by any means, then the function will run again because the flag (hasCodeRunBefore) will have been removed.
Good news...
Using localStorage can be tedious because of operators and long winded function names. I created a basic module to simplify this, so the above code would be replaced with:
window.onload = function () {
if (!ls.exists('has_code_run_before')) {
/** Your code here... **/
ls.set.single('has_code_run_before', true);
/** or... you can use a callback. **/
ls.set.single('has_code_run_before', true, function () {
/** Your code here... **/
});
}
};
Update #1
Per #PatrickRoberts comment, you can use the in operator to see if a variable key exists in localStorage, so
if (localStorage.getItem('hasCodeRunBefore') === null)
becomes
if (!('hasCodeRunBefore' in localStorage))
and is less verbose and a lot cleaner.
Secondly, you can set values as you would an object (localStorage.hasCodeRunBefore = true) though it will be stored as a string, not as boolean (or whatever data type your value is).
function toBeExecutedOnFirstLoad(){
// ...
}
if(localStorage.getItem('first') === null){
toBeExecutedOnFirstLoad();
localStorage.setItem('first','nope!');
}
All JavaScript must execute every time a page loads. If the script is on the page, it will execute.
The logic that is executed within the JavaScript included on the page may execute in a different manner depending on the page state, input provided, and any other signals it receives, be it from the server or the client.
If you're using a server side language, you might choose to render a script conditionally, such as the first time a user logs in.
If you need to include the javascript irrespective of context, then you need to listen to other signals.
The simple modern solution is to make use of localStorage. localStorage can be used to store custom string values on custom key values for any given domain.
The code to make use of this would look like:
if (localStorage['...my key here...'] === '...my expected value here...') {
// The page has been visited before
} else {
// The page has not been visited before
// OR
// The user or script has cleared the localStorage value
}
localStorage['...my key here...'] = '...my expected value here...';
That's all well and good if you just need things to work on the client alone. Sometimes you might need the server to know whether or not the page has been visited before.
The (less)simple solution is to use document.cookie:
if (/(?:^|;\s*)...my key here...=...my expected value here...(?:;|$)/.test(document.cookie)) {
// the page has been visited before
} else {
// The page has not been visited before
// OR
// The user or script has cleared the cookie
}
document.cookie = '...my key here...=...my expected value here...';
If you need to defer the execution until the page has finished loading, then simply include the script in an onload callback, either by assigning the event to the window:
window.onload = function () {
// do stuff when the page has loaded
//this will override any other scripts that may have been assigned to .onload
};
or by binding the event handler to the window:
window.addEventListener('load', function () {
// do stuff when the page has loaded
}, false);
It depends on what first page load means to you. It's subjective.
If you want the function to fire once the DOM has been parsed, but only the HTML and no other external resources, bind it to the DOMContentLoaded event.
document.addEventListener('DOMContentLoaded', fn);
Otherwise, if you want to wait for external resources to be loaded and then fire the event, you should bind it to the window object's load event like so:
window.addEventListener('load', fn);
Here are some links from the Mozilla Developer Network that explain the what I just said in more detail:
https://developer.mozilla.org/en-US/docs/Web/Events/load
https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded
Good luck!
I was facing something similar, the difference in my case was, I wanted to run a code whenever a new instance was being created I needed a certain code to execute, and then later for the rest of the reloads that code should not execute.
For that similar to localStorage solutions above use session storage instead:
fun_RunOnlyOnFirstPageLoad(){}
if(!$window.sessionStorage.getItem(hasRunBefore)){
fun_RunOnlyOnFirstPageLoad();
$window.sessionStorage.setItem(hasRunBefore, true);
}
using the window.sessionStorage instead stores the value only for that session.
this way once the tab is closed (session is over, that value is wiped out) and on every new instantiation, the code is executed.

IE11 script onload not working (sometimes)

I am currently working on a data-intensive web application that frequently communicates with an external API and retrieves JSONP data when returned. The script depends upon a library called head.js v1.0.3. http://headjs.com/ to accomplish this. However, I noticed that in IE 11 for some reason, the onload event for the script sometimes, but not always, fires before the script has actually loaded into the browser. The behavior is demonstrable whether using head.js or not. Alternatively, I may create a script element with the onload event set to capture the returned data. Sometimes it works, and sometimes not. Even more weird is that once it happens the first time, it seems to keep happening for the duration of the browser session.
Any ideas for a workaround?
Here is some example code:
//somejson.js
/*
window["queryResult"] = {blah:'blah'}
*/
function loadScript() {
head.load("/somejson.js", afterScriptLoad)
}
function afterScriptLoad() {
var result = queryResult
//Throws error because window.queryResult is sometimes undefined
}
After a little bit of research, it seems the only way around this bug is to modify the API so that once the variable holding the JSONP is initialized, the script itself triggers the callback. Unfortunately, this would not work as a solution for others if they do not have access to modify whatever API is in use, but it does solve the problem for me.
//somejson.js
/*
window["queryResult"] = {blah:'blah'}; scriptCallback()
*/
function loadScript(callback) {
var c = new afterScriptLoad(callback)
window["scriptCallback"] = c
head.load("/somejson.js", c)
}
function afterScriptLoad(callback) {
var retrieved = false
return function () {
if (!retrieved) {
retrieved = true
callback(queryResult)
}
}
}
function myCallback(response) {
//do something
}

Set data inside getCurrentPosition function

I'm doing next:
First thing - I'm checking if I already have loaded latitude and longitude data. If I do have, I'm saving that into array named "location".
Second thing - if I don't have any loaded data, I'm trying to get current position. After that, I'm trying to save latitude and longitude for current position.
And, at the end, I'm calling setMap(); function where I check location array and where I'm generating a map.
Problem:
Well, as I said it...inside "getCurrentPosition", I'm trying to set current position into "location" array, and after that I'm trying to take those values inside setMap(); function. Here's the problem, but only when i set "location" values inside "getCurrentPosition". If I set "location" values manually before (from "data" array), everything works fine.
Also, when I call a setMap() function inside "getCurrentPosition", everything works fine...but when I call it from outside, won't work.
Can someone explain me what's going on and what can I do?
Here's my code:
location = new Array();
if (data.lat) {
location['lat'] = data.lat;
location['lng'] = data.lng;
} else {
if (!navigator.geolocation) {
//
} else {
navigator.geolocation.getCurrentPosition(function(position) {
location['lat'] = position.coords.latitude;
location['lng'] = position.coords.longitude;
});
}
}
setMap();
Thank you.
You are setting a different variable inside of getCurrentPosition.
I would suggest researching variable scope.
Check out this question.
--edit--
I did not realize that the function you were using was a part of Javascript, I thought you had written/gotten it from somewhere.
Also, I stand corrected about the scope. Since you are using an array, the scope is fine, you should be able to set it inside the callback function just fine.
I ran your code and got some strange printouts when I did a console.log on location.
I took a guess, and it appears that location is a reserved word. I bet that if you change the name of location to something else, your code should work fine.
--edit--
I should have realized this sooner actually, since location is the same as window.location, which is the browser bar location!

Having a callback when a function is called without touching the actual function (jquery)?

I'm developing a small plugin that changes the favicons if there are unread messages in mailbox in Roundcubemail. However, the API sucks, and the event listupdate is fired only when the whole page is loaded, even if it is meant to fire when the list is updated.
However, I've managed to find out, that every time the list is updated, certain functions are called, such as set_unread_count. It gets the unread-count easily, so it would be great to somehow "append" stuff to this function. I just think based on hours of searching that there is no solution for this. Can I add a callback to be called when the set_unread_count is called? Can I somehow append stuff to that function? Any other ideas?
Create a little hook.
var _old_set_unread_count = set_unread_count;
set_unread_count = function() {
// do whatever you want here
// access arguments[x] to get arguments.
_old_set_unread_count.apply(this, arguments);
};
Demo: http://www.jsfiddle.net/4yUqL/69/

Categories

Resources