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。

相关推荐
an31742几秒前
解决 VSCode 中 ESLint 格式化不生效问题:新手也能看懂的配置指南
前端·javascript·vue.js
Lee川2 小时前
🚀《JavaScript 灵魂深处:从 V8 引擎的“双轨并行”看执行上下文的演进之路》
javascript·面试
汪汪队长2 小时前
谷歌浏览器自定义油猴插件
前端
ZFSS2 小时前
SeeDance Tasks API 的对接和使用
前端·人工智能
睿智的仓鼠2 小时前
🦞OpenClaw 快速部署及使用指南
前端·人工智能
前端付豪2 小时前
Nest 项目小实践之图书增删改查
前端·node.js·nestjs
比特鹰2 小时前
手把手带你用Flutter手搓人生K线
前端·javascript·flutter
大雨还洅下2 小时前
前端JS: 数组扁平化
javascript
奔跑路上的Me2 小时前
前端导出 Word/Excel/PDF 文件
前端·javascript
bluceli2 小时前
JavaScript异步编程深度解析:从回调到Async Await的演进之路
前端·javascript