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。

相关推荐
ejinxian1 小时前
Rust GUI框架Azul与Electron、WebView2
前端·javascript·electron
IT_陈寒2 小时前
Vue的v-for里用index当key,我被自己坑惨了
前端·人工智能·后端
代码不加糖2 小时前
0基础搭建前后端分离项目:实现菜单与界面左右布局
java·前端·javascript·mysql·elementui·mybatis
zhensherlock3 小时前
Protocol Launcher 系列:Tally 快速计数器的深度集成
前端·javascript·typescript·node.js·自动化·github·js
AC赳赳老秦3 小时前
OpenClaw权限管理实操:团队共享Agent,设置操作权限,保障数据安全
服务器·开发语言·前端·javascript·excel·deepseek·openclaw
光影少年3 小时前
Polyline 组件如何绘制渐变区域?
前端·javascript·掘金·金石计划
Pkmer3 小时前
古法编程: React思维模型快速建立
前端·react.js
普通网友3 小时前
JavaScript:ESLint+Prettier 规范代码格式
开发语言·javascript·ecmascript
jiayong234 小时前
第 38 课:任务列表里高亮当前正在查看详情的任务
开发语言·前端·javascript·vue.js·学习
anOnion4 小时前
构建无障碍组件之Spinbutton Pattern
前端·html·交互设计