1. // 捕获404页面,并重定向
    2. const isRunUrl = function (url) {
    3. return new Promise(function (resolve, reject) {
    4. // 测试链接连通性, 主要检测404错误
    5. // 由于AJAX通常无法区分404和跨域问题,所以只能用script 或者 link标签,link比script更容易捕获错误
    6. var dom = document.createElement('link');
    7. dom.href = url;
    8. dom.rel = 'stylesheet';
    9. document.head.appendChild(dom);
    10. dom.onload = function () {
    11. document.head.removeChild(dom);
    12. resolve();
    13. }
    14. dom.onerror = reject;
    15. });
    16. }
    17. isRunUrl("测试地址").then(
    18. (res) => {
    19. // 处理resolve的代码
    20. console.log("ok", data);;
    21. }, (err) => {
    22. // 处理reject的代码,重定向逻辑
    23. console.log("err", err);
    24. }
    25. )