简体   繁体   中英

How to Enable Right-Click In NightmareJS?

I'm currently testing in NightmareJS using different viewports and agents. I'm automating visits to a site that has a lot of complex scripting and styles. I'm not able to sufficiently duplicate the agent and view in a separate test browser such that the site displays the same content for me as it does when I'm visiting with Nightmare. For this reason, I need to be able to right-click elements in Nightmare's Electron window so that I can inspect specific elements in the DOM.

The problem is that right-click is disabled in the Electron window. I found this answer which describes adding code to the render process:

// Importing this adds a right-click menu with 'Inspect Element' option
const remote = require('remote')
const Menu = remote.require('menu')
const MenuItem = remote.require('menu-item')

let rightClickPosition = null

const menu = new Menu()
const menuItem = new MenuItem({
  label: 'Inspect Element',
  click: () => {
    remote.getCurrentWindow().inspectElement(rightClickPosition.x, rightClickPosition.y)
  }
})
menu.append(menuItem)

window.addEventListener('contextmenu', (e) => {
  e.preventDefault()
  rightClickPosition = {x: e.x, y: e.y}
  menu.popup(remote.getCurrentWindow())
}, false)

Note: this code would probably need to be altered as mentioned in the referenced answer but where would I add such code when working with Nightmare?

The main script isn't the same as the Electron render process script AFAIK. As for that sort of solution, this would probably be a better one but how to invoke?

Currently there is no available api for right click in nightmare, reference issue:

https://github.com/segmentio/nightmare/issues/346

A possible solution could be to use Electron directly bypassing nighmarejs.

Example (no tested):

webpage.sendEvent('contextmenu')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM