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。

相关推荐
pan_junbiao11 分钟前
Vue3.0组合式API:setup()函数
前端·javascript·vue.js
黄毛火烧雪下12 分钟前
React 中,Hook 是一个特定的概念
前端·javascript·react.js
正小安15 分钟前
Vue 3 中 useRouter 与 useRoute 的深度解析
前端·javascript·vue.js
Missying5518 分钟前
vue前端实现下载导入模板文件
前端·vue.js·elementui·html
洗发水很好用18 分钟前
vue2制作高复用页面
前端·javascript·vue.js
533_22 分钟前
[vue] vue-seamless-scroll 滚动到第二遍的时候不能进行点击的问题
前端·javascript·vue.js
jiaoxingk26 分钟前
Selenium如何通过js注入避免被检测
javascript·selenium·测试工具
2301_7969821426 分钟前
requests-html的详细使用方法
前端·python·html
Mr-Apple1 小时前
orangepi部署web环境
android·前端·adb
苍穹之跃1 小时前
python之协程
开发语言·前端·python