简体   繁体   English

获取电子中的webview中的单击元素

[英]Get the clicked element inside webview in electron

I'm building an electron app with a webview embedded in it. 我正在构建一个嵌入了Webview的电子应用程序。 Just like this. 像这样。

index.html 的index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Hello World!</title>
</head>
<body>
  <webview
      id="webview"
      src="https://www.google.com/search?q=search&tbm=isch"
  />
  <script>
    require('./renderer.js')
  </script>
</body>
</html>

I would like to get the tagName of the element on which the user right-clicked, and I want to do something with the element if it's img . 我想获得用户在其上单击鼠标右键的元素的tagName,并且如果该元素是img ,我想对该元素做一些事情。 Here's what I tried. 这是我尝试过的。

renderer.js renderer.js

document.getElementById("webview").addEventListener("contextmenu", event => {
  if (event.target.tagName === "img") {
    const src = event.target.src;
    // do something with src
  }
});

It doesn't work, because event.target is always the embedded webview itself. 它不起作用,因为event.target始终是嵌入式webview本身。 No matter what I clicked. 无论我点击什么。 How to make it work? 如何使其运作?

you can't. 你不能。 WebView in Electron is special kind, spawning a separate, isolated process to host contents other than parents, end up most of inner elements are inaccessible via normal html interfaces. Electron中的WebView是一种特殊的方法,它产生了一个单独的,独立的进程来承载除父级以外的其他内容,最终大多数内部元素都无法通过常规html接口访问。 Instead, you have to manually setup some IPC between process for specific desired behavior, like webview's preload script sets up ipc listener, and parent send some ipc to webview or vice versa. 相反,您必须在进程之间手动设置一些IPC以实现特定的所需行为,例如webview的预加载脚本设置ipc侦听器,父级将一些ipc发送到webview,反之亦然。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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