用户脚本不适用于所有网页

时间:2017-03-07 12:38:00

标签: javascript jquery userscripts tampermonkey tooltipster

以下脚本适用于大多数静态网站和超链接,但它目前在维基及其他动态生成的内容中存在问题呈现工具提示。

在调用tooltipster()之前,我甚至使用超时等待加载所有内容,但这仍然没有呈现工具提示。

setTimeout(function() {
    $('a.tooltipster').tooltipster({
        theme: 'tooltipster-punk'
    });
}, 5000);

它适用于jQueryMDN等网站,但不适用于WikipediaReddit

Userscript

// ==UserScript==
// @name         Link Hover
// @namespace    default
// @version      1.0.0
// @description  Display link.
// @author       Mr. Polywhirl
// @match        *://*/*
// @require      https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.slim.min.js
// @require      https://cdnjs.cloudflare.com/ajax/libs/tooltipster/3.3.0/js/jquery.tooltipster.min.js
// @resource     tt_CSS https://cdnjs.cloudflare.com/ajax/libs/tooltipster/3.3.0/css/tooltipster.min.css
// @resource     ttTheme_CSS https://cdnjs.cloudflare.com/ajax/libs/tooltipster/3.3.0/css/themes/tooltipster-punk.min.css
// @grant        GM_addStyle
// @grant        GM_getResourceText
// @grant        GM_log
// ==/UserScript==
(function() {
    'use strict';
    GM_addStyle([
        GM_getResourceText('tt_CSS'),
        GM_getResourceText('ttTheme_CSS')
    ].join(''));

    (function($) {
        $.fn.setLinkTitle = function() {
            return this.attr('title', processLink(this.attr('href')));
        };
    })(jQuery);

    $(function() {
        $('a').each((index, link) => {
            $(link).addClass('tooltipster').setLinkTitle();
        }).tooltipster({
            theme: 'tooltipster-punk'
        });
    });

    function processLink(path) {
        return !isPathAbsolute(path) ? relPathToAbs(path) : path;
    }

    // http://stackoverflow.com/a/25833886/1762224
    function relPathToAbs(sRelPath) {
        var nUpLn, sDir = "", sPath = location.pathname.replace(/[^\/]*$/, sRelPath.replace(/(\/|^)(?:\.?\/+)+/g, "$1"));
        for (var nEnd, nStart = 0; nEnd = sPath.indexOf("/../", nStart), nEnd > -1; nStart = nEnd + nUpLn) {
            nUpLn = /^\/(?:\.\.\/)*/.exec(sPath.slice(nEnd))[0].length;
            sDir = (sDir + sPath.substring(nStart, nEnd)).replace(new RegExp("(?:\\\/+[^\\\/]*){0," + ((nUpLn - 1) / 3) + "}$"), "/");
        }
        return location.protocol + '//' + location.host + sDir + sPath.substr(nStart);
    }

    function isPathAbsolute(path) {
        return /^(?:\/|[a-z]+:\/\/)/.test(path);
    }
})();

1 个答案:

答案 0 :(得分:0)

根据Lookups package的建议,我使用了URL API并使用了原始HTML元素属性。

我还添加了一种突出协议和主机名的方法。

// ==UserScript==
// @name         Link Hover
// @namespace    http://tampermonkey.net/
// @version      1.2.1
// @description  Display link.
// @author       Mr. Polywhirl
// @match        *://*/*
// @require      https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.slim.min.js
// @require      https://cdnjs.cloudflare.com/ajax/libs/tooltipster/3.3.0/js/jquery.tooltipster.min.js
// @resource     tt_CSS https://cdnjs.cloudflare.com/ajax/libs/tooltipster/3.3.0/css/tooltipster.min.css
// @grant        GM_addStyle
// @grant        GM_getResourceText
// @grant        GM_log
// ==/UserScript==
(function() {
    'use strict';
    GM_addStyle([
        GM_getResourceText('tt_CSS'),
        // Derived from the tooltipster-punk theme.
        '.tooltipster-green {',
        '  border-radius: 5px; ',
        '  border-bottom: 3px solid #7EB;',
        '  background: #2a2a2a;',
        '  color: #DFE;',
        '}',
        '.tooltipster-green .tooltipster-content {',
        '  font-family: Consolas, Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, sans-serif;',
        '  font-size: 14px;',
        '  line-height: 16px;',
        '  padding: 8px 10px;',
        '}',
         'span[class^="tt-protocol-"] {',
        '  color : #F44;',
        '}',
        '.tt-protocol-https {',
        '  color : #0F0 !important;',
        '}',
        '.tt-hostname {',
        '  color : #FF0;',
        '}'
    ].join(''));

    const tooltipConfig = {
        theme: 'tooltipster-green',
        contentAsHTML : true,
        multiple : true
    };

    (function($) {
        $.fn.setLinkTitle = function() {
            this[0].title = $.processLink(this[0].href);
        };
        $.processLink = function(url) {
            try {
                var urlObj = new URL(url); // Parse URL as an object.
                return url.replace(urlObj.protocol, function(protocol) {
                    return $('<span>').addClass('tt-protocol-' + protocol.replace(':', '')).text(protocol).prop('outerHTML');
                }).replace(urlObj.hostname, function(hostname) {
                    return $('<span>').addClass('tt-hostname').text(hostname).prop('outerHTML');
                });
            }
            catch (e) {
                return url;
            }
        };
    })(jQuery);

    $(function() {
        createTooltips();

        if ('MutationObserver' in window) {
            document.addEventListener('DOMNodeInserted', createTooltips, false);
        } else {
            setInterval(createTooltips, 100);
        }
    });

    function createTooltips() {
        $('a:not(.tooltipstered)').each((index, link) => {
            $(link).addClass('tooltipster').setLinkTitle();
        }).tooltipster(tooltipConfig);
    }
})();