Global variable isn't holding? - javascript

This should be a really easy "derp" question, but here it is:
I'm trying to set up a global variable in a JS file so that I can control when an action triggers. In my case, I want okBoxCall to only be called if firstTime is true. I have firstTime set to true initially, then I change it to false afterwards. My code is NOT working as it should however, as it still calls up okBoxCall more than once.
var Dialog;
var HUDWindow;
var smartPhone;
var firstTime = true;
$(document).ready(function(){
smartPhone = new SmartPhone();
initDialog();
initHUDWindow();
if(firstTime == true)
{
okBoxCall("Tutorial", "Welcome to McLarin Energy!");
firstTime = false;
}
});
What am I doing wrong? Obviously firstTime is not holding its change to false...
EDIT Forgot to mention that this is for a 3D game, not web pages. Cookies are not used.

I'm guessing you want to check whether this is the first time the user opens a page and open a tutorial if it is?
It is not possible the way you want to do it. Every time your page is loaded your script is evaluated again. So this means a variable firstTime is created and it is set to true. What you need is some persistent storage on the client to store whether it is the first time or not. You will need to set a cookie or call the localStorage API if you don't bother disregarding older browsers.

Your function should only be called once due to $(document).ready(...). So, I'm guessing you're reloading the page to get the alert to display again and again...
Maybe you should be looking at using cookies, not just a plain old JS variable..?

What is okBoxCall doing? If you have any error in okBoxCall firstTime = false will not be executed. Set the value before you call okBoxCall.
$(document).ready(function(){
smartPhone = new SmartPhone();
initDialog();
initHUDWindow();
if(firstTime == true)
{
firstTime = false;
okBoxCall("Tutorial", "Welcome to McLarin Energy!");
}
});

Related

How to automatically reload a web page

I want my website page to reload once when it has already opened for the first time. I wrote this function in my javascript file for that...
var i;
$(document).ready(function(){
for ( i=0;i<1;i++){
if(i===0){
location.reload();
break;
}
}
});
But the page keeps reloading again and again as if the above function was a recursive one.
How do I do this?
P.S I'm doing it because of this issue.
<script type='text/javascript'>
(function() {
if( window.localStorage ) {
if( !localStorage.getItem('firstLoad') ) {
localStorage['firstLoad'] = true;
window.location.reload();
} else
localStorage.removeItem('firstLoad');
}
})();
</script>
Here is what's happening:
The page loads for the first time, jQuery calls any handlers on the document.ready event
The page reloads
The document.ready call is made again
repeat
Out of curiosity, why would you want to do that? And why do you have a for loop that will run for one iteration?
Also, to answer your question as far as I know the only way to make sure the page doesn't reload is use a cookie that lasts for about 5 seconds. Then, on document.ready check for that cookie and if it exists then don't reload.
You must either set a cookie (or use javascript's localStorage), or use xhr to retrieve a value held on a remote server.
If you want to use cookies, it's as simple as
document.cookie = "username=John Doe";
where the document.cookie is a query string of the form (x=y;a=b;n=z)
If you want the page to reload every time the user vists, be sure to unset the cookie once you've done any necessary processing when a page reload has been set.
$( window ).load(function() {
if (window.location.href.indexOf('reload')==-1) {
window.location.replace(window.location.href+'?reload');
}
});
Code is ok. But if the page is opened from another page with a link to an id (.../page.html#aa) the code only works with firefox. With other browsers reload the page without going to id. (Sorry for my english).
I found the solution with this code. It is assumed that the page is refreshed no earlier than one hour. Otherwise, add minutes to the oggindex variable.
<script>
var pagina = window.location.href;
var d = new Date();
var oggiindex = d.getMonth().toString()+'-'+d.getDate().toString()+'-'+d.getHours().toString();
if (localStorage.ieriindex != oggiindex)
{
localStorage.setItem("ieriindex", oggiindex);
window.location.replace(pagina);
}
</script>
Yours code executed each time $(document).ready(), so it's not surprise that your loop is infinity - each load finished as ready state.
If you give more detailed requirements we can solve it with no using window object as data holder. It's bad way but you can set it for test.
Window object stores variables not depend on reload because it's higher then document.
Let's try:
if( window.firstLoad == undefined ){
// yours code without any loop
// plus:
window.firstLoad = false;
}
You can make it with localStorage API.
Check this link also, it's giving more information about window object variables:
Storing a variable in the JavaScript 'window' object is a proper way to use that object?

Will javascript loop make my page get eventually stuck?

i have this function:
<script language="javascript">
function live(){
var d = $live;
var elm = document.getElementById("live");
if(d==1){
elm.style.display = 'block';
} else{
elm.style.display = 'none';
}
}
</script>
setInterval(function(){live();},10000);
and im just concerned about my page getting stuck after having it open on the browser for a while or causing my users browser to stop responding or anything like that. How safe is to use loops like this?
Is this what google or facebook use to show new notifications alerts on their page in real time? That seems to go pretty smoothly.
Thank you.
This isn't a loop in the traditional sense, it's really just a function which is called at a regular interval, so you are in the clear here. Just be careful that nothing increases the memory use each time it executes, as that is what will most likely be what will kill the user's browser.
Also, the setInterval needs to me in a script tag, otherwise it will show up on your page.
Use of setInterval is a common practice for showing notifications on websites. It wont hang your page, although you must clear the interval once it is no longer required. Say you have already shown the notification, so better hold the reference of setInterval so that you could clear it later.
var ref = setInterval(fn, 100);
clearInterval(ref);

Is there a method within Omniture's s.code to see whether a pageview has fired?

I'm looking to develop a Omniture "trouble" tag that will fire within Google Tag Manager. This tag should check to see whether the Omniture s.code on-page has fired a pageview. If it hasn't, send an Event to our GA account.
Ideally, it'd look like this (pseudocode follows):
<script>
window.onload=function(){if(OmniturePageViewHasFired == false){
ga('send','event','SCodeMissing','Page',window.location.href);
}}
</script>
Just checking to see whether the s.code is on page at all is a much easier task, but won't be as useful since it's possible for the code to be on page and not have fired. Any ideas? Also note that I do NOT have access to the s.code itself, so I can't set a variable with it that's then picked up by this script.
This is how I'd do it, based on how Adobe's DigitalPulse Debugger looks for it:
function OmniturePageViewHasFired() {
var i=document.images;
for (var c=0,l=i.length;c<l;c++) {
if ( (i[c].src.indexOf('/b/ss/')>=0)
&& (!i[c].src.match(/[&?]pe=/))
) return true;
}
for (var o in window) {
if ( (o.substring(0,4)=='s_i_')
&& (window[o].src)
&& (window[o].src.indexOf('/b/ss/')>=0)
&& (!window[o].src.match(/[&?]pe=/))
) return true;
}
return false;
}
//example:
if (OmniturePageViewHasFired() == false){
// no omn request detected
} else {
// found at least 1
}
Note 1: This will only return true if a page view (s.t) request is made. It will not return true for click requests (s.tl). If you want it to return true for any request, then remove the last &&.. in the 2 conditions.
Note 2: Officially Adobe thinks it is good enough to just look for /b/ss/ in the src. Admittedly, in all my years of QA'ing Adobe Analytics (btw that's what it's called now, not Omniture), I've only seen a false positive from this like one or two times.
If this worries you, you can make the condition more specific by evaluating the domain of the src for your implementation. This is unique to your implementation, which is why Adobe doesn't look for something more specific. Just look at a request on your page to get it.
You can add your own code to track whether or not Omniture has fired.
There is a plugin feature, and Omniture uses to fire plugins and other code on a tracking event. This function is fired everytime a pageview or on-click event, or any other type of Omniture event is fired.
You'll want to make sure that this is not used elsewhere to enable Omniture plugins, if it is, you'll have to be able to update that code. Basically you could do something like the following, as long as you make sure that the following bit of code loads and exectues (after) the s_code.js file loads and executes:
var om_fired = false;
s.usePlugins=true;
function s_doPlugins(s) {
om_fired = true;
}
s.doPlugins=s_doPlugins;
Then in your google code just check to see if om_fired is true/false
Another way to do it (adding it here since it was too long for a comment).
Before s.code loads, add some script that reads the cookies that are set by Omniture, I don't remember the exact cookie names, but multiple cookies are set. Your code that reads the cookie will need to be in the header so it fires as the page loads( and before site cat tracking code), and before page load completes. Read the omniture cookie, and check the values, there is one in there for Time Since Last hit, I believe the cookie variable is something like s.tlh. Store that value away, then after page load fire another call that reads the cookie again and check to see if the tlh value changed. If it did then your tracking event occured. If it did not change, then your event did not fire. Your challenge will be to make sure the code fires in the right order, i.e. 1. Read cookie/store value, 2. Site Cat Fires, 3. Read cookie again and compare w/ cookie in #1.

Check if window.history.go successful?

Is there anyway to check if a window.history.go command is successful in changing the window.location or not?
i.e. If I do a window.history.go(-5) when there are only 3 pages in the history stack, the browser will do nothing.
Is there a way to check if that happens and run other code? An error callback, of sorts.
Thanks.
For an immediate response, first you'll want to check history.length to make sure it is at least 6, e.g. to go -5. Apart from that, I think the only way is to use setTimeout and if the script is still running, the callback will be executed.
Not really a JS expert, but if you want to perform some action when the user goes back or forward, you could use URL hashes and trigger some function using the jQuery onhashchange event. This will not give you the position in history, and i'm also not sure about cross-browser compatibility, but it did the job for me so far.
$(window).on('load' function(){
var hash = parent.top.location.hash;
if(hash == '' || hash == '#' || hash == null){
//if none, set a hash and reload page
parent.top.location.hash = '#/some/hash';
parent.top.location.reload(true);//use true if you dont want to use cached items
}
});
$(window).on('hashchange', function(){
do_something(parent.top.location.hash);
});
function do_something(hash){
//this function will be executed each time the '#' changes
console.log('hash changed to '+hash);
}

FF extension: saving a value in preferences and retrieving in the js file

I am making an extension which should take a link as the user input only once. Then the entire extension keeps using that link on various functions in the JS file. When the user changes it, the value accessed by the js file also changes accordingly.
I am using the following but it does not work for me
var pref_manager = Components.classes["#mozilla.org/preferencesservice;1"].getService(Components.interfaces.nsIPrefService)
function setInstance(){
if (pref_manager.prefHasUserValue("myvar"))
{
instance = pref_manager.getString("myvar");
alert(instance);
}
if(instance == null){
instance = prompt("Please enter webcenter host and port");
// Setting the value
pref_manager.setString("myvar", instance);
}
}
instance is the global variable in which i take the user input. The alert (instance) does not show up, which means there is some problem by the way i am saving the pref or extracting it.
Can someone please help me with this. I have never worked with preferences before. so even if there are minor problems i might not be able to figure out.
I don't have my own code in front of me to compare right now, but all of the above looks ok to me. My guess is that your problem is that you didn't set a default value for your preference, because I think Firefox will ignore preferences without a default value specified.
See:
https://developer.mozilla.org/en/Adding_preferences_to_an_extension
use "pref_manager.getCharPref("prefname")" if the preference is a string. You could also have:
pref_manager.getBoolPref("prefname"); // boolean (true/false) preferences
and
pref_manager.getIntPref("prefname"); // numbers

Categories

Resources