移动端网站(m. h5. mobile. touch.)

在移动设备中,将 www. 或根域名智能跳转到 m./h5./mobile./wap./touch./3g.移动版。电脑浏览器油猴请勿安装此脚本(调试除外)

目前为 2025-04-26 提交的版本。查看 最新版本

// ==UserScript==
// @name         移动端网站(m. h5. mobile. touch.)
// @namespace   https://greasyfork.org/users/1171320
// @version      0.1
// @description  在移动设备中,将 www. 或根域名智能跳转到 m./h5./mobile./wap./touch./3g.移动版。电脑浏览器油猴请勿安装此脚本(调试除外)
// @author         yzcjd
// @author2       ChatGPT4 辅助
// @match        *://www.*/*
// @match        *://*.*/*
// @exclude      *://m.*/*
// @exclude      *://h5.*/*
// @exclude      *://mobile.*/*
// @exclude      *://wap.*/*
// @exclude      *://touch.*/*
// @exclude      *://3g.*/*
// @run-at       document-start
// @grant        none
// @license      MIT
// ==/UserScript==

(function () {
    'use strict';

    const isMobile = /Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent);
    if (!isMobile) return;

    if (sessionStorage.getItem('__mobile_redirected__')) return;

    const hostname = location.hostname;
    const path = location.pathname + location.search + location.hash;
    const originHost = hostname.replace(/^www\./i, '');
    const mobilePrefixes = ['m.', 'h5.', 'mobile.', 'wap.', 'touch.', '3g.'];

    (async () => {
        for (const prefix of mobilePrefixes) {
            const mobileHost = prefix + originHost;
            const mobileUrl = location.protocol + '//' + mobileHost + path;
            const mobileHomeUrl = location.protocol + '//' + mobileHost + '/';

            try {
                const res = await fetch(mobileUrl, { method: 'HEAD' });
                if (res.ok) {
                    sessionStorage.setItem('__mobile_redirected__', '1');
                    location.href = mobileUrl;
                    return;
                } else {
                    console.warn(`[同路径失败] ${mobileUrl} 状态:${res.status}`);
                }
            } catch (e) {
                console.warn(`[同路径请求错误] ${mobileUrl}`, e);
            }

            // 如果路径失败,尝试首页
            try {
                const resHome = await fetch(mobileHomeUrl, { method: 'HEAD' });
                if (resHome.ok) {
                    sessionStorage.setItem('__mobile_redirected__', '1');
                    location.href = mobileHomeUrl;
                    return;
                } else {
                    console.warn(`[首页失败] ${mobileHomeUrl} 状态:${resHome.status}`);
                }
            } catch (e) {
                console.warn(`[首页请求错误] ${mobileHomeUrl}`, e);
            }
        }
        console.info('[提示] 未找到可用移动页面,停留当前PC页面');
    })();
})();