标签 js 下的文章

查询tabs

function queryTabs(queryOptions) {
    return new Promise((resolve, reject) => {
        chrome.tabs.query(queryOptions, (result) => {
            if (chrome.runtime.lastError) {
                reject(chrome.runtime.lastError);
            } else {
                resolve(result);
            }
        });
    });
}

后台和内容脚本通信

接收方

chrome.runtime.onMessage.addListener( (request, sender, sendResponse) =>{
        console.log(`receive message: `, request);
        
        sendResponse({msg: 'msg'}); 
    //表示异步操作,不会立刻关闭消息接收
    return true; 

发送方

chrome.runtime.sendMessage({type: "query"}, (res) => {
        console.log("返回结果 ", res);
    });

mouse event

function createMouseEvent(eventType, rect) {
    return new MouseEvent(eventType, {
        bubbles: true,
        cancelable: true,
        view: window,
        clientX: rect.left + rect.width / 2,  // 元素的水平中心
        clientY: rect.top + rect.height / 2,  // 元素的垂直中心
        screenX: window.screenX + rect.left + rect.width / 2,  // 相对于屏幕的位置
        screenY: window.screenY + rect.top + rect.height / 2,  // 相对于屏幕的位置
        button: 0  // 左键
    });
}

const rect = ele.getBoundingClientRect();
ele.dispatchEvent(createMouseEvent('mousedown', rect));
ele.dispatchEvent(createMouseEvent('mouseup', rect));
ele.dispatchEvent(createMouseEvent('click', rect));  // 模拟 click 事件

point event

function createPointerEvent(eventType, rect) {
    return new PointerEvent(eventType, {
        bubbles: true,
        cancelable: true,
        view: window,
        clientX: rect.left + rect.width / 2,
        clientY: rect.top + rect.height / 2,
        screenX: window.screenX + rect.left + rect.width / 2,
        screenY: window.screenY + rect.top + rect.height / 2,
        button: 0,
        pointerId: 1,  // 指针 ID,一般使用 1
        width: 1,      // 指针宽度
        height: 1,     // 指针高度
        pressure: 0.5  // 模拟的触控压力,0-1 范围
    });
}