javascript - 如何在 Tampermonkey 中捕获状态 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);
推荐阅读
- python - Scrapy - 比 start_urls 优先的下一个链接
- microsoft-graph-api - 如何使用 Microsoft Graph API 拨打电话号码?
- kubernetes - 在 k8s 中,如何在复制控制器中部署 pod?
- php - 我想要一个动态的 id,即如果我删除 id 2,则 id 3 变为 Id 2
- javascript - javascript计算器和模拟器
- php - 如果迁移文件不存在但迁移表中的条目可用,我如何解决迁移问题
- r - 是否有用于查找矢量化方程的梯度和 Hessian 的 R 函数或包?
- javascript - 将画布 blob 添加到表单数据
- java - 在TestNG中,dependonfunction如何用于继承
- c# - 在 Stripe Customer 对象 C# 中访问元数据时遇到问题