Any jQuery,页面注入jQuery,方便控制台调试代码

write once run anywhere,注入jQuery,方便控制台调试代码,这是增强版,原始版请参考v0.2.1

Version vom 17.09.2020. Aktuellste Version

// ==UserScript==
// @name         Any jQuery,页面注入jQuery,方便控制台调试代码
// @namespace    http://bbs.91wc.net/any-jquery.htm
// @version      0.3.0
// @description  write once run anywhere,注入jQuery,方便控制台调试代码,这是增强版,原始版请参考v0.2.1
// @author       Wilson
// @match        http*://*/*
// @require      https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js
// @resource     jquery https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js
// @grant        unsafeWindow
// @grant        GM_getResourceText
// @grant        GM_registerMenuCommand
// @grant        GM_unregisterMenuCommand
// @grant        GM_setValue
// @grant        GM_getValue
// ==/UserScript==

//jQuery注入成功后执行
function afterInject() {
    //Your codes here


    //你也可以像这样向页面中写全局变量或函数
    //_g.a="test a";
    //_g.b = function(){
    //   console.log("test b");
    //}
}

function initJQ(){
    //初始化_jq变量
    _g._jq = _g.jQuery;
    _g._jq.version=_g._jq.fn.jquery;
};

function initMyInfo(){
    //脚本信息
    _g.myinfo = {};
    _g.myinfo.name=GM_info.script.name;
    _g.myinfo.ver=GM_info.script.version;
    _g.myinfo.jqurl=GM_info.script.resources[0].url;
};

function injectJquery(){
    if(_g._jq === null){
        setTimeout(function(){
            //动态设置jQuery
            var jq_code = GM_getResourceText('jquery');
            $("body").append('<script id="_g_jquery">'+jq_code+'</script>');

            //初始化_jq变量
            initJQ();
            //call afterInject
            afterInject();
        }, 0);
    } else {
        //初始化_jq变量
        initJQ();
        //call afterInject
        afterInject();
    }
};

//防冲突
this.$ = this.jQuery = jQuery.noConflict(true);
//注入jQuery和全局变量_g
$("body").append(`<script id="_g_script">var _g=window, _w=_g, _jq=(typeof jQuery === "undefined") ? null : jQuery;</script>`);
//注入脚本信息
initMyInfo();
//注入jQuery
var __jq_switch = GM_getValue("__jq_switch")||"open";
if(__jq_switch=="open"){
    injectJquery();
}


//开关
var jquerySwitchMenu =function(type, callback){
    var closeMenu, closeCallback = function(){
        if(callback) callback("close");
        if(closeMenu) GM_unregisterMenuCommand(closeMenu);
        openMenu = GM_registerMenuCommand("立即注入", openCallback);
    }
    var openMenu, openCallback = function(){
        if(callback) callback("open");
        if(openMenu) GM_unregisterMenuCommand(openMenu);
        closeMenu = GM_registerMenuCommand("取消注入", closeCallback);
    }
    if(type==="open"){
        closeMenu=GM_registerMenuCommand("取消注入", closeCallback);
    } else {
        openMenu=GM_registerMenuCommand("立即注入", openCallback);
    }
};
jquerySwitchMenu(__jq_switch, function(type){
    GM_setValue("__jq_switch", type);
    if(type=="open"){
        injectJquery();
        alert("注入成功");
    }else{
        alert("取消成功,下次刷新生效");
    }
});