jQuery-如果浏览器选项卡是焦点,那么执行AJAX-不工作

jQuery - If browser tab is focused, then do AJAX - Not working

本文关键字:执行 AJAX- 工作 焦点 浏览器 如果 选项 jQuery-      更新时间:2023-09-26

我有一个代码,用于确定当前浏览器窗口或选项卡是否处于活动状态。如果它是活动的,标签的标题会显示"活动",如果不是,则会显示"模糊"

它运行良好。这是代码:

 $(window).on("blur focus", function (e) {
            var prevType = $(this).data("prevType");
            if (prevType != e.type) {   //  reduce double fire issues
                if (e.type == "blur") {
                    document.title = 'blurred';
                } else if (e.type = "focus") {
                  document.title = 'focus';
                }
            }
            $(this).data("prevType", e.type);
        })

上面的代码运行良好。

现在,如果我在其中添加AJAX,它就不起作用了。

 $(window).on("blur focus", function (e) {
            var prevType = $(this).data("prevType");
            if (prevType != e.type) {   //  reduce double fire issues
                if (e.type == "blur") {
                    document.title = 'blurred';
                } else if (e.type = "focus") {
                    var interval = function () {
                        $.ajax({
                            url: "<?php echo base_url('home/get') ?>",
                            cache: false,
                            success: function (html) {
                                $("#text").val(html);
                                document.title ='focus';
                            },
                        });
                    };

                    setInterval(interval, <?php echo $int ?>);
                }
            }
            $(this).data("prevType", e.type);
        })

如果它在焦点上,它会说是焦点。如果我失去焦点,它会在不到一秒钟的时间里显示"模糊",然后再次显示焦点。我不知道为什么。如果它不在焦点上,我想说模糊。添加AJAX代码并不能使其工作。

请帮忙。谢谢

您需要在blur事件中使用clearTimeout()。我的代码不断地轮询我的服务器以获取数据,但当我离开页面时,它会停止轮询。请看下面的实现。我在这里的应用程序中也做了类似的操作:

$(window).blur(function() {
    clearTimeout(getJsonTmr);
    clearTimeout(updatePreviewTmr);
}).focus(StartTimers);
function StartTimers () {
    // Every half a second, 
    getJsonTmr = setInterval(function () {
        $.get("/doodles/update?getJson&DoodleID=" + DoodleOptions.DoodleID, function (data) {
            data = JSON.parse(data);
            if (!DoodleOptions.isActive)
                clearDoodleCanvas();
            $.each(data, function (index) {
                drawFromStream(data[index]);
            });
        });
    }, 500);
    updatePreviewTmr = setInterval(function () {
        $.post("/doodles/update?updatePreview", {
            "DoodleID": DoodleOptions.DoodleID,
            "DoodlePreview": canvas.toDataURL()
        });
    }, 5000);
}
StartTimers();

您可以使用上面的代码作为参考并更改您的代码。

为您提供一个简单的参考实现

function timers() {
  tmrAjax = setInterval(function () {
    $.get(/* ... */);
  }, 1000);
}
timers();
$(window).blur(function () {
  clearInterval(tmrAjax);
}).focus(timers);