chrome插件模拟isTrusted的事件

文章目录


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

方法

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

  • manifest中声明debugger的权限
    manifest.json:
{
    "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发出请求
// 该函数的作用是:通过触发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的点击
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。

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值