开发者

How can i determine if a site 404'd in javascript and then redirect the browser somewhere else

开发者 https://www.devze.com 2023-02-07 19:33 出处:网络
I am trying to write a gre开发者_Python百科asemonkey script for firefox that will check a site on opening and see if the website 404\'d and then redirect the user automatically somewhere else.

I am trying to write a gre开发者_Python百科asemonkey script for firefox that will check a site on opening and see if the website 404'd and then redirect the user automatically somewhere else.

Thanks


// ==UserScript==
// @name           Redirect
// @namespace      test
// @include        *
// ==/UserScript==

if (/^about:neterror/.test(document.documentURI))
{
    location.assign(...);
}


Make an AJAX request to the URI and check the response code from the returned XHR object for the 404 error code (or != 200).

Do you have access to some kind of JS Framework?


By "check a site", I assume you mean a url on a different domain.

This can't be done strictly from the client side without "cooperation" from the target service due to client side cross-site security restrictions, and I imagine that is not your use case.

A common solution is to use some kind of server side proxy.

If you use a page on your site to act as the proxy, you can make it flexible enough to accept requests to check any URL.

  • make a resource page on your site, e.g. checkRemotePage.php
  • checkRemotePage.php calls the target site's page and obtains response code
  • call your page /checkRemotePage.php via ajax to get the data it retrieved

If your needs are limited to a static url or a small list of url prefixes, you can use apache mod_proxy

  • enable mod_proxy
  • use a ProxyPass entry /check_remote_page http://www.somehost.com/the_rest_of_the_url
0

精彩评论

暂无评论...
验证码 换一张
取 消