chrome插件模拟isTrusted的事件

文章目录

使用js模拟的事件isTrusted的值时false。有的时候我们想要模拟sTrusted未true的事件就比较麻烦了。
我们可以利用chrome插件的 chrome.debugger解决改问题。

方法

大体思路是:模拟事件的请求从content_script.js发出,到达background.js进行模拟。

  • manifest中声明debugger的权限
    manifest.json:
js 复制代码
{
    "manifest_version": 3,
    "name": "test",
    "description": "test",
    "version": "0.0.1",
    "background": {
        "service_worker": "background.js"
    },
    "action": {
        "default_popup": "./dist/index.html"
    },
    "content_scripts": [
        {
            "js": [
                "content_script.js"
            ],
            "run_at": "document_start"
        }
    ],
    "permissions": [
        "debugger",
    ]
}
  • content_script.js发出请求
js 复制代码
// 该函数的作用是:通过触发element身上的mousedown事件来触发element的点击事件
function openDebuggerToClick(element) {
  return new Promise((resolve, reject) => {
    console.log('click目标是', element)
    const x = element.getBoundingClientRect().left + 5
    const y = element.getBoundingClientRect().top + 5

    // 根据按钮的mousedown事件来触发点击事件
    element.addEventListener(
      'mousedown',
      function (e) {
        if (!e.isTrusted) {
          e.preventDefault()
          let obj = { x, y }
          chrome.runtime.sendMessage(
            {
              action: 'mousedownToClick',
              params: obj
            },
            function (response) {
              console.log('响应结果是', response)
              if (response.code === 200) {
                resolve('click success')
              } else {
                reject('click fail')
              }
            }
          )
        }
      },
      true
    )
    // 触发click
    element.dispatchEvent(
      new MouseEvent('mousedown', {
        bubbles: true,
        cancelable: true
      })
    )
  })
}
  • background.js处理请求,模拟isTrusted未true的点击
js 复制代码
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
 if (request.action === 'mousedownToClick') {
    const { params } = request
    impMousedownToClick(params, sender, sendResponse)
  }
  return true
})
//  ----------------------mouseDown模拟点击跳过限制----------------
const impMousedownToClick = (params, sender, sendResponse) => {
  chrome.debugger.attach({ tabId: sender.tab.id }, '1.2', function () {
    console.log('接收到content的消息---------', params, sender)
    let flag = true
    // sendResponse({ yourEvent: '正在调整, 需要时间生效' })
    const xC = params.x
    const yC = params.y
    //通过触发鼠标的按下和抬起事件来触发点击事件
    chrome.debugger.sendCommand(
      { tabId: sender.tab.id },
      'Input.dispatchMouseEvent',
      { type: 'mousePressed', x: xC, y: yC, button: 'left', clickCount: 1 },
      function () {
        if (chrome.runtime.lastError) {
          console.error(chrome.runtime.lastError.message)
          flag = false
          return
        }
      }
    )
    chrome.debugger.sendCommand(
      { tabId: sender.tab.id },
      'Input.dispatchMouseEvent',
      {
        type: 'mouseReleased',
        x: xC,
        y: yC,
        button: 'left',
        clickCount: 1
      },
      function () {
        console.log('鼠标弹起完成_ 处理返回逻辑')
        if (chrome.runtime.lastError) {
          console.error(chrome.runtime.lastError.message)
          flag = false
          return
        }
        setTimeout(() => {
          if (flag) {
            sendResponse({ code: 200, message: '点击成功' })
          } else {
            sendResponse({ code: 500, message: '点击失败' })
          }
          chrome.debugger.detach({ tabId: sender.tab.id }, () => {
            console.log('取消attach')
          })
        }, 5000)
      }
    )
  })
}

原理

什么是isTrusted属性?在web api官方网站mozilla.org有如下解释:"Event接口的 isTrusted 属性是一个只读属性,它是一个布尔值(Boolean)。当事件是由用户行为生成的时候,这个属性的值为 true ,而当事件是由脚本创建、修改、通过 EventTarget.dispatchEvent() 派发的时候,这个属性的值为 false 。"

所以如果我们使用Chrome DevTools Protocol协议的Input.dispatchMouseEvent接口,触发的事件isTrusted就为true。

相关推荐
上海合宙LuatOS9 分钟前
LuatOS核心库API——【fatfs】支持FAT32文件系统
java·前端·网络·数据库·单片机·嵌入式硬件·物联网
m0_5287490026 分钟前
linux编程----目录流
java·前端·数据库
集成显卡26 分钟前
前端视频播放方案选型:主流 Web 播放器对比 + Vue3 实战
前端·vue·音视频
前端 贾公子26 分钟前
Vue3 业务组件库按需加载的实现原理(中)
前端·javascript·vue.js
温轻舟27 分钟前
前端可视化大屏【附源码】
前端·javascript·css·html·可视化·可视化大屏·温轻舟
北极象27 分钟前
Flying-Saucer HTML到PDF渲染引擎核心流程分析
前端·pdf·html
weixin1997010801628 分钟前
Tume商品详情页前端性能优化实战
大数据·前端·java-rabbitmq
梦里寻码28 分钟前
深入解析 SmartChat 的 RAG 架构设计 — 如何用 pgvector + 本地嵌入打造企业级智能客服
前端·agent
edisao34 分钟前
第一章:L-704 的 0.00% 偏差
前端·数据库·人工智能
CappuccinoRose36 分钟前
HTML语法学习文档(一)
前端·学习·html