Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch status 503 in tampermonkey

I have a userscript that refreshes the page every second, but sometimes the website it's trying to refresh runs into the status 503 error, and that stops the script from running anymore. That means that script will no longer try refresh the page every second. How do I keep the script running after the page runs into the status 503 error? The error looks like this in the console:

Failed to load resource: the server responded with a status of 503 (Service Unavailable)

// ==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
like image 649
frosty Avatar asked Nov 08 '22 01:11

frosty


1 Answers

The user-script run at page load, they won't run if page does not load at all for any status code other than 200. You can use <iframe> as @Hemanth suggested but you have to break the infinite loop as the <iframe> will also load the user-script and so on. To break it just check if the user-script is loaded on the top window.

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
}

Complete Code:

(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);
like image 176
Munim Munna Avatar answered Nov 14 '22 06:11

Munim Munna