Github HTML Preview Button (HTML 预览按钮)

Adds a button to preview HTML files on Github using htmlpreview. 添加一个按钮以使用 htmlpreview 在 Github 上预览 HTML 文件。

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name         Github HTML Preview Button (HTML 预览按钮)
// @namespace    http://tampermonkey.net/
// @version      0.1.1
// @description  Adds a button to preview HTML files on Github using htmlpreview. 添加一个按钮以使用 htmlpreview 在 Github 上预览 HTML 文件。
// @author      cjm
// @match        https://github.com/*
// @grant        none
// @license MIT
// ==/UserScript==

(function() {
    'use strict';

    const func = ()=>{
        var element = document.getElementById("wocao3");
        element && element.parentNode.removeChild(element);

        if (window.location.href.endsWith('.htm') || window.location.href.endsWith('.html')) {
            const url = window.location.href;
            const btn1 = `<a id="wocao3" class="btn ml-2 d-none d-md-block" style="
background: #171a1c;
    color: white;
    display: inline-block !important;
    /*width: 48%;*/
    text-align: center;
    /*margin: 5px;*/
    " target="_blank" href="${`http://htmlpreview.github.io/?${url}`}">` + 'HTML Preview' + '</a>'

            const parent = document.querySelector('.pagehead-actions > li:last-child');
            //.pagehead-actions   //#repository-container-header
            parent.insertAdjacentHTML('beforeBegin', btn1);
        }
    }

    func();

    window.addEventListener('hashchange', ()=>{
        func();
    }
    )

    //修改native以拦截popstate事件
    var pushState = history.pushState;
    history.pushState = function() {
        var ret = pushState.apply(history, arguments);
        window.dispatchEvent(new Event("pushstate"));
        window.dispatchEvent(new Event("locationchangefathom"));
        return ret;
    }

    window.addEventListener("popstate", function() {
        window.dispatchEvent(new Event("locationchangefathom"))
    });
    window.addEventListener("locationchangefathom", trackPageview)
    function trackPageview() {
        func();
    }

}
)();