How to catch status 503 in tampermonkey

后端 未结 3 488
粉色の甜心
粉色の甜心 2021-01-13 15:23

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 ru

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-13 16:04

    The problem is that location.reload attempts to completely replace the page with a reloaded version, but if the browser fails to connect to the server, the page will not be loaded, and any userscripts for that page will fail to run, because there's no page for them to run on.

    A workaround would be to use a Javascript network request to fetch the text of the new page, and then replace the existing content with the new content with Javascript - if the response is a 503 error (or some other error), you can simply ignore it and try again. This ensures that you'll always stay on the same (loaded) page, so the userscript will continue running indefinitely, even if the responses sometimes fail.

    Here's an example of a userscript that updates StackOverflow's homepage every 10 seconds with new HTML. You can use DOMParser to transform response text into a document that can be navigated with querySelector, among other things:

    // ==UserScript==
    // @name         Update SO
    // @namespace    CertainPerformance
    // @version      1
    // @match        https://stackoverflow.com/
    // @grant        none
    // ==/UserScript==
    
    const container = document.querySelector('.container');
    function getNewData() {
      console.log('getting new data');
      fetch('https://stackoverflow.com',
        {
          // The following is needed to include your existing cookies with the request, which may be needed:
          credentials: "same-origin"
        })
        .then((resp) => {
          // If there are errors, such as a 503 error, proceed directly to the `finally` to try again:
          if (!resp.ok) return;
          return resp.text();
        })
        .then((text) => {
          const doc = new DOMParser().parseFromString(text, 'text/html');
          container.innerHTML = doc.querySelector('.container').innerHTML;
        })
        .finally(() => {
          // Whether there was an error or not, try to refresh again in a few seconds:
          setTimeout(getNewData, 10000);
        });
    }
    
    setTimeout(getNewData, 10000);
    

提交回复
热议问题