brrd/electron-tabs

How to open the target blank hyperlinks inside the tab content in a new tab

ajithjacob05 opened this issue · 2 comments

The target blank hyperlinks inside the tab content is opening currently in a new electron container after passing "allowPopups: true" to webviewAttributes. But my requirement is to open those hyper links in a new Tab. How can we achieve this?. The main.js "win.webContents.setWindowOpenHandler(url)" is not getting invoked. So just tried "tab.webview.setWindowOpenHandler(url)?, but with no luck.

Please refer the below code snippet

Looking forward to getting information or solution on opening hyperlinks in new electron-tab.


let tab = tabGroup.addTab({
    title: 'Dummy',
    src: 'dummy.html',
    active: true,
    closable: false,
    webviewAttributes: {
      preload: './preload.js',
      allowPopups: true
    },
    ready: tab => {
      tab.webview.setWindowOpenHandler(({ url }) => {
        console.log(url);
      })
    }
  });

dummy.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Dummy</title>
</head>
<body>
  <button onclick="clickHandler()" >Open Google</button>
  <a href="https://google.com/" target="_blank">https://google.com/</a>
  <script>
    function clickHandler() {
      window.open("https://google.com/", "_blank");
    }
  </script>
</body>
</html>
brrd commented

webview.setWindowOpenHandler() doesn't exist in electron API: https://www.electronjs.org/docs/latest/api/webview-tag

What you are looking for is webContents.setWindowOpenHandler(): https://www.electronjs.org/docs/latest/api/web-contents#contentssetwindowopenhandlerhandler

The webContents you need is the one related to the webview, not the window's one. Electron used to provide a method webview.getWebContents() but it's now deprecated, so you will have to write your own function to get it: https://www.electronjs.org/docs/latest/breaking-changes#deprecated-webviewgetwebcontents

Thank you!