mylib

我的工具

Version vom 07.07.2024. Aktuellste Version

Dieses Skript sollte nicht direkt installiert werden. Es handelt sich hier um eine Bibliothek für andere Skripte, welche über folgenden Befehl in den Metadaten eines Skriptes eingebunden wird // @require https://update.greasyfork.org/scripts/435697/1406786/mylib.js

// ==UserScript==
// @name mylib
// @description 我的工具
// @grant GM_setValue
// @grant GM_getValue
// ==/UserScript==
;(function(win){
    const My =function(){//构造函数,需配合实例方法,与this,prototype有关
        const e=document.documentElement.firstElementChild,sv=GM_setValue,gv=GM_getValue;
        if(e.tagName==='Z'){
            My.zone=e;
            My.btns=e.querySelector('my-btns');
        }else {
            win.cl=win.console.log;win.al=win.alert; // win.gv=gv;win.sv=sv
            My.zone=My.before('z',e,'',`class`,'rwf');
            My.addStyle(`my-a{border-style: inset}my-btns{display:block;z-index:9195129;position:fixed;height: min-content;}.my-btn{user-select: none;font-size: initial !important;}`,'my-btns');
            My.btns=My.append('my-btns',My.zone,'',`class`,'rwf');
            if(!gv('fixbar',0)||win.top!==win.self) My.prototype.bindDrag(My.btns);
            My.btns.style.left=gv('left',0);
            My.btns.style.top=gv('top',0);
            My.btns.onmouseup=e=>{
                sv('left',My.btns.style.left);
                sv('top',My.btns.style.top);
            }
            My.addBtns(function 拽(){}).children[0].oncontextmenu=e=>{//右键 固定/不固定 按钮组
                e.preventDefault();//取消默认
                sv('fixbar',gv('fixbar')?0:1);
                location.reload();
            }
        }
        return My;
    }
    //My.静态方法 My.prototype实例方法(如本案例中my.prototype.constructor.toString())
    My.addStyle=function(css,className='rwf'){//function和lambda this指向不同,后者没有prototype、arguments,后者不能new/作为构造函数,
        return My.append('style',My.zone,css,`class`,className);
    }
    My.append=function(...args){//my.append('tag',document.body,'content','idk','true','data-s')
        const [tagName, targetEle, innerHTML, ...attributes]=args;
        const ele=document.createElement(tagName);
        ele.innerHTML=innerHTML;
        for (let i=0; i < attributes.length; i += 2) ele.setAttribute(attributes[i], attributes[i + 1]);
        targetEle.append(ele);
        ele.on = function (event, handler) {
            this.addEventListener(event, handler);
            return this; // 支持链式调用
        };
        return ele;
    }
    My.after=function(...args){//my.after('div',document.body,'','suck','1','dick',000)
        const [tagName, targetEle, innerHTML, ...attributes]=args;
        const ele=document.createElement(tagName);
        ele.innerHTML=innerHTML;
        for (let i=0; i < attributes.length; i += 2)ele.setAttribute(attributes[i], attributes[i + 1]);
        targetEle.after(ele);
        ele.on = function (event, handler) {
            this.addEventListener(event, handler);
            return this; // 支持链式调用
        };
        return ele;
    }
    My.before=(...args)=>{// my.before('div',document.head,'','suck','1','dick')
        const [tagName, targetEle, innerHTML, ...attributes]=args;
        const ele=document.createElement(tagName);
        ele.innerHTML=innerHTML;
        for (let i=0; i < attributes.length; i += 2) ele.setAttribute(attributes[i], attributes[i + 1]);
        targetEle.before(ele);
        ele.on = function (event, handler) {
            this.addEventListener(event, handler);
            return this; // 支持链式调用
        };
        return ele;
    }
    My.addBtns=(...args)=>{//my.addBtns(()=>{},e=>{confirm(e.target.id)},function(e){prompt(e.target.outerHTML)},function test(e){return 1})
        const len=args.length;
        for(let i=0;i<len;i++){
            const btn= My.append('input',My.btns,'','type','button','class','my-btn','value',args[i].name);
            btn.addEventListener('click',args[i]);
        }
        return My.btns;
    }
    My.eods=()=>{//enable or disable style in My.zone
        My.zone.querySelectorAll('style').forEach(e=>{
            e.type==='0'?e.type='':0
        });
    }
    My.sohe=(...args)=>{//show or hide elements
        args.forEach(e=>{
            if(typeof e!=="string") e.style.display==='none'?e.style.display='initial':'none';
            else {
                document.querySelectorAll(e).forEach(e=>{
                    e.style.display==='none'?e.style.display='initial':'none'
                });
            }
        });
    }
    My.s2d=(seconds)=>{//seconds2date//my.s2d(new Date().getTime())
        const date=new Date(seconds),year=date.getFullYear(),month=date.getMonth()+1,day=date.getDate(),
              hour=date.getHours(),minute=date.getMinutes(),second=date.getSeconds(),milliseconds=date.getMilliseconds(),currentTime=year+"-"+month+"-"+day+" "+hour+":"+minute+":"+second+":"+milliseconds;
        return currentTime;
    }
    My.tieba=(uname,pwd)=>{
        document.querySelector('[name="userName"]').value=uname;
        document.querySelector('[name="password"]').value=pwd;
        return document.querySelector('[value="登录"]').click();
    }
    My.fixTitle=()=>{//disable title change
        Object.defineProperty(document,"title",{
            writable:false
        });
    }
    My.addAs=(...urls) => {//my.addAs("https://www.bilibili.com/","https://www.baidu.com/")
        return urls.map(url => {
            const match = url.match(/:\/\/(www\.)?([^\/]+)/);
            if (match && match[2]) {
                const domainParts = match[2].split('.'),name=domainParts.length > 1 ? domainParts.slice(0, -1).join('.') : url=domainParts[0];
                My.append('a',My.btns,name,`href`,url,'class','my-a');
            }
            return null;
        });
    }
    My.prototype.bindDrag=(ele)=>{//鼠标拖动
        ele.onmousedown=function(ev){//if(ev.target.tagName==='TEXTAREA') return;
            const diffX=ev.clientX-ele.offsetLeft,diffY=ev.clientY-ele.offsetTop,iw=win.innerWidth,ih=win.innerHeight;
            document.onmousemove=function(ev){
                let moveX=ev.clientX-diffX,moveY=ev.clientY-diffY;
                moveX<0?moveX=0:moveX>iw-ele.offsetWidth?moveX=iw-ele.offsetWidth:0
                moveY<0?moveY=0:moveY>ih-ele.offsetHeight?moveY=ih-ele.offsetHeight:0;
                ele.style.left=moveX/iw*100+'%'//moveX + 'px';
                ele.style.top=moveY/ih*100+'%'//moveY + 'px'
            }
            document.onmouseup=function(ev){
                this.onmousemove=null;
                this.onmouseup=null;
            }
        }
    }
    My.sleep=(time)=>{
        return new Promise((resolve) => setTimeout(resolve, time));
    }
    My.waitForElement=(selector,timeout=3e4)=>{//查找ele.30000
        return new Promise((resolve, reject) => {
            const intervalTime=500;
            const startTime=Date.now();
            const interval=setInterval(() => {
                const element=document.querySelector(selector);
                if (element) {
                    clearInterval(interval);
                    resolve(element);//找到则返回函数
                } else if (Date.now() - startTime > timeout) {
                    clearInterval(interval);
                    reject(`Timeout waiting for element ${selector}`);//超时则返回字符串
                }//继续寻找
            }, intervalTime);
        });
    }
    My.waitForElements=(selector,timeout=3e4)=>{//查找eles
        return new Promise((resolve, reject) => {
            const intervalTime=500,startTime=Date.now(),interval=setInterval(() => {
                const elements=document.querySelectorAll(selector);
                if (elements) {
                    clearInterval(interval);
                    resolve(elements);//找到则返回函数
                } else if (Date.now() - startTime > timeout) {
                    clearInterval(interval);
                    reject(`Timeout waiting for element ${selector}`);//超时则返回字符串
                }//继续寻找
            }, intervalTime);
        });
    }
    win.my=new My();
})(unsafeWindow);