Javascript: Master tab

1

I need a certain function in a project, I need some functions to only execute in a tab of my site, for example ... The user is in the HOME tab but the SOBRE , CONTATO tabs are open and on that site plays audio depending on what return of a query in PHP . So I do not want all the tabs doing that same search (which I do every 3 seconds), and I do not want to play the audio on all the tabs (they will not have only those pages on that site), so I created a function using sessionStorage and localStorage, follows:

    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) p>

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

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

    
asked by anonymous 10.06.2014 / 02:52

1 answer

1

If the tab change is done via ajax, save the current tab name to 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 tab of the site is a separate page, generated by PHP, you have two alternatives:

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

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

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

    return;

}
    
10.06.2014 / 14:16