我需要在活动的浏览器选项卡上运行脚本。如果打开的选项卡很少,则仅在激活时运行它。如果隐藏了所有选项卡,则仅在上次访问(非关键)或任何单个选项卡时运行脚本。
我编写了代码,但是sumtimes焦点事件不会触发。
var page_id = $page_id; //unique id
// write page id in array in cookie
var pages = [];
if ($.cookies.get('pages') != null) {
pages = $.cookies.get('pages');
}
//set active page to false
pages[page_id] = false;
//if none of opened pages are active set current page active
var count = 0;
$.each(pages, function( index, value ) {
if (value == true) {
count++;
}
});
if (count == 0) {
pages[page_id] = true;
$.cookies.set('pages', pages, {hoursToLive: .1});
}
// if current page is active run script
if (pages[page_id] == true) {
run_script();
}
$(function() {
// on page focus
$(window).focus(function() {
pages = $.cookies.get('pages');
//if empty cookies write current page in cookie
if (jQuery.isEmptyObject(pages)) {
pages = {};
pages[page_id] = true;
// non of pages are active write current page as active
} else {
var count = 0;
$.each(pages, function( index, value ) {
if (index == page_id) {
count++;
pages[index] = true;
} else {
pages[index] = false;
}
});
if (count == 0) {
pages[page_id] = true;
}
}
$.cookies.set('pages', pages, {hoursToLive: .1});
});
});
//before close page delete it's id from cookie
window.onbeforeunload = function() {
var pages = {};
if ($.cookies.get('pages') != null) {
pages = $.cookies.get('pages');
}
delete pages[page_id];
$.cookies.set('pages', pages, {hoursToLive: .1});
};
// if empty cookie write current page
window.setInterval(function(){
pages = $.cookies.get('pages');
if (jQuery.isEmptyObject(pages)) {
pages = {};
pages[page_id] = true;
}
$.cookies.set('pages', pages, {hoursToLive: .1});
}, 1000);