LoginSignup
0
0

More than 5 years have passed since last update.

Electronのwebviewの`new-window`イベントで取得できるurlが`about:blank`になってしまう

Last updated at Posted at 2018-06-16

webviewのnew-window イベントを使って別ウインドウへのリンクをブラウザに飛ばす。
というやつをやりたかったのだが、callbackで得られるurlが about:blank になってしまって開く先のURLがわからないという問題に遭遇した。

https://github.com/electron/electron/issues/1458
このissueっぽいが治ってない?
issueの一番新しいコメントで言われている方法で解決してみたメモ。

<body onload="onLoad()">
  <webview src="https://paper.dropbox.com/"></webview>
</body>
let clientX, clientY
function onLoad() {
  const {shell} = require('electron')
  const webview = document.querySelector('webview')
  window.addEventListener('mousedown', e => {
    // mousedownイベント時に座標を保存しておく
    clientX = e.clientX;
    clientY = e.clientY;
  })
  webview.addEventListener('dom-ready', () => {
    webview.addEventListener('new-window', (e) => {
      e.preventDefault();
      const bbox = webview.getBoundingClientRect();
      const guestPageX = clientX - bbox.left;
      const guestPageY = clientY - bbox.top;
      // 座標からaタグを取得し、そこからhrefを取得する
      const script = 'document.elementFromPoint('+guestPageX+','+guestPageY+')["href"]'
      webview.executeJavaScript(
        "document.elementFromPoint(".concat(guestPageX, ",", guestPageY, ")['href']"),
        false,
        (realURL) => {
          shell.openExternal(realURL);
        }
      );
    })
  })
}
</script>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0