Javascript: Master Tab

Asked

Viewed 234 times

1

I need a certain function in a project, I need some functions only run in a tab of my site, for example... The user is in the tab HOME but the flaps SOBRE, CONTATO are open and on this site plays an audio depending on what return of a query in a PHP. So I don’t want all tabs doing this same search (I do +/- every 3 seconds), and I don’t want to play the audio in all tabs (there won’t be only these pages on this site), so I created a function using sessionStorage and localStorage, below:

    var app = {};

app.getTime = function()
{
    // retornar em segundos
    return new Date().getTime().toString().substring(0,10);
};

if( !sessionStorage['window']) sessionStorage['window'] = Math.floor(Math.random()*(9999999999999999-1111111111111111+1)+1111111111111111);

(app.fn = function()
{

    // Se não tiver setado o localStorage['time'] a menos de 3 sec
    // esta será a janela mestre.
    if( !localStorage['window'] || parseInt(localStorage['time'])<(app.getTime()-3))
    {

        localStorage['window'] = sessionStorage['window'];
    }

    app.mestre = (sessionStorage['window'] == localStorage['window']);

    if( app.mestre)
    {

        localStorage['time'] = app.getTime();
    }

    clearInterval(app.time);

    app.time = setInterval(function(){ app.fn(); }, 1000);

})();

///////////////

// EXEMPLO... Só a janela mestre fará a contagem...

var cont = 1;

setInterval(function(){

    if( app.mestre) document.body.innerHTML += cont++ + '  ';

}, 1000);

Jsfiddle (Open at least twice by clicking on the link - Duplicate Tab does not work)

What happens is that when I duplicate the Aba as said the sessionStorage of the tabs are equal, IE, goes wrong...

How to solve and what I can do to improve the code ?

1 answer

1

If the tab change is done via ajax, save the name of the current tab in a global variable at the time of the change.

aba = "Home";

or

aba = "Contato";

Then, inside the setInterval:

setInterval(function(){

    if(aba != "Home"){

        return; //se não for a aba home, sai da função antes de executar o cálculo.

    }

    if( app.mestre) document.body.innerHTML += cont++ + '  ';

}, 1000);

Now, if each site tab is an independent page, generated by PHP, you have two alternatives:

1 - Or put the script only in the home tab; 2 - Check if we are at home looking for an element.

Take the id of an element that only exists on the home of your site, in this case the homeId. If this element does not exist, make the function return null before performing the code. Place at the beginning of the function app.fn:

var homeId = document.getElementById('homeId');
if (homeId == null){

    return;

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.