Searene
Searene

Reputation: 27584

Get the clicked element inside webview in electron

I'm building an electron app with a webview embedded in it. Just like this.

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. Here's what I tried.

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. No matter what I clicked. How to make it work?

Upvotes: 2

Views: 1966

Answers (1)

OJ Kwon
OJ Kwon

Reputation: 4641

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. 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.

Upvotes: 1

Related Questions