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

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

// ==UserScript==
// @name         移动端网站(m. h5. mobile. touch.)
// @namespace   https://greasyfork.org/users/1171320
// @version      0.2
// @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.'];

    function tryRedirect(mobileHost) {
        const mobileUrl = location.protocol + '//' + mobileHost + path;
        const mobileHomeUrl = location.protocol + '//' + mobileHost + '/';

        const img = new Image();
        img.onload = function() {
            console.log('[跳转] 检测到移动版存在,跳转到:', mobileUrl);
            sessionStorage.setItem('__mobile_redirected__', '1');
            location.href = mobileUrl;
        };
        img.onerror = function() {
            console.warn('[警告] 当前路径不存在,尝试跳转到移动首页');
            // 尝试跳首页
            const imgHome = new Image();
            imgHome.onload = function() {
                console.log('[跳转] 移动首页存在,跳转到:', mobileHomeUrl);
                sessionStorage.setItem('__mobile_redirected__', '1');
                location.href = mobileHomeUrl;
            };
            imgHome.onerror = function() {
                console.warn('[提示] 移动首页也不存在,停留当前页面');
            };
            imgHome.src = mobileHomeUrl + 'favicon.ico?_t=' + Date.now(); // 加点参数防缓存
        };
        img.src = mobileUrl + 'favicon.ico?_t=' + Date.now(); // 加点参数防缓存
    }

    (async () => {
        for (const prefix of mobilePrefixes) {
            const mobileHost = prefix + originHost;
            tryRedirect(mobileHost);
            break; // 注意:只测试第一个匹配前缀
        }
    })();
})();