javascript - 如何在 tampermonkey 中捕获状态 503

标签 javascript error-handling settimeout tampermonkey http-status-code-503

我有一个每秒刷新页面的用户脚本,但有时它尝试刷新的网站会遇到状态 503 错误,这会停止脚本运行。这意味着脚本将不再尝试每秒刷新页面。如何在页面运行状态 503 错误后保持脚本运行?错误在控制台中看起来像这样:

加载资源失败:服务器响应状态为 503(服务不可用)

// ==UserScript==
// @name        script
// @namespace   name
// @description example
// @match       *^https://example.com/$*
// @version     1
// @require     https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js
// @grant       GM_xmlhttpRequest
// @run-at document-end
// ==/UserScript==

//*****************************************START OF SET_TIMEOUT
var timeOne = 1000;
var theTime = timeOne;

var timeout = setTimeout("location.reload(true);", theTime);
function resetTimeout() {
clearTimeout(timeout);
timeout = setTimeout("location.reload(true);", theTime);
} //end of function resetTimeout()
//*****************************************END OF SET_TIMEOUT

最佳答案

用户脚本在页面加载时运行,如果页面根本没有加载除 200 以外的任何状态代码,它们将不会运行。您可以使用 <iframe>正如@Hemanth 建议的那样,但你必须打破无限循环作为 <iframe>还将加载用户脚本等。要打破它,只需检查用户脚本是否加载到顶部窗口。

if (window == window.top) {
    // Remove everything from the page
    // Add an iframe with current page URL as it's source
    // Add an event to reload the iframe few seconds after it is loaded
}

完整代码:

(function ($) {
  'use strict';
  var interval = 5000;
  if (window == window.top) {
    var body = $('body').empty();
    var myframe = $('<iframe>')
      .attr({ src: location.href })
      .css({ height: '95vh', width: '100%' })
      .appendTo(body)
      .on('load', function () {
        setTimeout(function () {
          myframe.attr({ src: location.href });
        }, interval);
      });
  }
})(jQuery);

关于javascript - 如何在 tampermonkey 中捕获状态 503,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52613406/

相关文章:

javascript - Laravel 5.2 - vue 集成

javascript - ShadowDOM 与文档片段——它们有何不同?

javascript - 如何将 settimeout 与 vue.js 观察者一起使用?

javascript - jQuery foreach 中的 setTimeout

javascript - 在 AngularJS 中手动加载和卸载外部 javascript

Python try/except 问题与 SMTPLib

angularjs - Node JS - Express JS 错误处理模式/实践

oracle - 根据参数记录错误

javascript - jQuery UI 对话框使用 setTimeout 自动关闭

javascript - 计算资源的可用性