Skip to content

window.open into another webview #15040

Closed

Description

@Gozala

Is your feature request related to a problem? Please describe.

Beaker browser uses <webview> elements for loading browser tab content. Unfortunately sites that depend on window.open() to return WindowProxy for cross site communication via postMessage break as Electron always returns null.

With an addition of webpreferences="nativeWindowOpen=yes" as described by window.open document it become possible to open links from with-in <webview> in a popup window and return BrowserWindowProxy for cross-site communication, but only if opened windows are popups, which does not allow an app (like Beaker) to provide any UI, or to open link in different <webview> as tab instead of window.

Describe the solution you'd like

Ideally event on <webview> (where window.open() was called) would dispatch an event, that would allow it's handler to decide where opened document should load into, so it could choose to either open a new Browser window or new <webview> or not to open at all.

Describe alternatives you've considered
I've attempted to somehow get browser window content rendered into <webview> but without any success.

I can't think of any other solution that would allow window.open() in the document with-in <webview> return WindowProxy.

Additional context
beakerbrowser/beaker#1194

Activity

  1. MarshallOfSound commented on Oct 9, 2018

    @MarshallOfSound
    Member

    See the new-window event, you can intercept window.open calls and provide you're own webContents.

    https://electronjs.org/docs/api/web-contents#event-new-window

  2. Gozala commented on Oct 9, 2018

    @Gozala
    Author

    See the new-window event, you can intercept window.open calls and provide you're own webContents.

    https://electronjs.org/docs/api/web-contents#event-new-window

    @MarshallOfSound That is not the case, as illustrated by the linked example https://github.com/Gozala/electron-quick-start/blob/window.open/renderer.js#L19 that is exactly what I'm doing.

    Truth is by the time new-window is dispatched new window has already being created and linked to corresponding BrowserWindowProxy. Also from what I can event.newGuest expects BrowserWindow and not a webContents.

  3. MarshallOfSound commented on Oct 9, 2018

    @MarshallOfSound
    Member

    So what you've got there is a classic IPC event async issue.

    The new-window event is actually emitted in the main process and expects newGuest to be set syncronously on firing of the event. Because this event is being proxied to the renderer over IPC it's actually impossible to respond syncronously from the renderer (IPC inherently makes it async).

    You'll need to respond to this event in the main process for your logic to work correctly.

    Although not documented for this specific events similar events do have the warning that event.preventDefault() won't work.

    E.g.https://electronjs.org/docs/api/webview-tag#event-will-navigate

  4. Gozala commented on Oct 9, 2018

    @Gozala
    Author

    So what you've got there is a classic IPC event async issue.

    The new-window event is actually emitted in the main process and expects newGuest to be set syncronously on firing of the event. Because this event is being proxied to the renderer over IPC it's actually impossible to respond syncronously from the renderer (IPC inherently makes it async).

    I was about to point out that message is send to the main process:

    const guestId = ipcRenderer.sendSync('ELECTRON_GUEST_WINDOW_MANAGER_WINDOW_OPEN', url, toString(frameName), toString(features))
    if (guestId != null) {
    return getOrCreateProxy(ipcRenderer, guestId)
    } else {
    return null
    }

    Would it make sense to send a message to the renderrer host and let it either respond or forward to to the main process instead ?

    You'll need to respond to this event in the main process for your logic to work correctly.

    Is that actually possible ? Given the renderrer is blocked it won't be able to create host webview.

    Although not documented for this specific events similar events do have the warning that event.preventDefault() won't work.

    Yeah I noticed that was a case, but it's also that example in window.open() does event.preventDefault().

  5. Gozala commented on Oct 9, 2018

    @Gozala
    Author

    @MarshallOfSound Can this be reopened as an issue then ?

  6. MarshallOfSound commented on Oct 9, 2018

    @MarshallOfSound
    Member

    Is that actually possible ?

    Yes, you can get the underlying web contents for your webview either by fetching it from webContents.fromId or from the will-attach-webview event. Then you add these window listeners in the main process.

    Yeah I noticed that was a case, but it's also that example in window.open() does event.preventDefault()

    That example code is commented to indicate it's running in the main process

    Can this be reopened as an issue then ?

    Currently what I'm seeing here I'd expected behavior

  7. Gozala commented on Oct 9, 2018

    @Gozala
    Author

    Yes, you can get the underlying web contents for your webview either by fetching it from webContents.fromId or from the will-attach-webview event. Then you add these window listeners in the main process.

    @MarshallOfSound either I'm not understanding what you're telling me or you're missing a detail, that is: When window.open() is called from the document with-in <webview> it will block the renderrer on IPC to main process:

    const guestId = ipcRenderer.sendSync('ELECTRON_GUEST_WINDOW_MANAGER_WINDOW_OPEN', url, toString(frameName), toString(features))
    if (guestId != null) {
    return getOrCreateProxy(ipcRenderer, guestId)
    } else {
    return null
    }

    Therefor I am not able to create a host <webview>, and an a consequence in new-window handler in the main process I won't have a host <webview> yet to get webcontents for. By the time renderrer get's a chance to create a host webview it's already too late.

    Am I misunderstanding something here ?

  8. Gozala commented on Oct 9, 2018

    @Gozala
    Author

    I've tried a workaround of sending a sync message to host renderrer from webview's preload script as I was hoping to create a patch that would send message to a host if it's in the webview or parent if it isn't but ended up with blocked webview.

  9. MarshallOfSound commented on Oct 9, 2018

    @MarshallOfSound
    Member

    @Gozala Full disclosure, never done this before and code I write here is untested 😆 Before I run through this using a webview it's worth noting you'll have a way better time using a BrowserView based architecture.

    Now let's try this, so in order to "open" a new window into a webview we need a few things.

    1. As you noted, window.open is synchronous and blocking meaning we can't ask the renderer to make us a new webview, that means we need a webview ready and waiting to receive an "opened" window.
    2. We need to do all this work in the main process because as previously noted event.preventDefault() and event.newGuest must be called / assigned synchronously when the event is initially emitter.

    Solving (1) is quite straightforward, we just have an empty webview element laying around all the time, as soon as it is used you make a new one. I.e.

    <webview src="about:blank" />
    <script>
    const { ipcRenderer } = require('electron');
    
    ipcRenderer.on('webview-used', () => {
      const webview = document.createElement('webview');
      webview.setAttribute('src', 'about:blank');
      document.body.appendChild(webview);
    });
    </script>

    Then in the main process we just need to keep a reference to the webContents of this "ready" webview.

    // Main Process
    let nextContents = null;
    
    mainWindow.webContents.on('did-attach-webview', (event, webContents) => {
      if (webContents.getURL() === 'about:blank') {
        nextContents = webContents;
      }
    });

    Now we have a pending webContents and a way to make new ones we just need to correctly intercept the window.open calls in the main process to solve (2).

    // Main Process
    function openNewWindowsInWebView (webContents) {
      webContents.on('new-window', (event) => {
        event.preventDefault();
        if (nextContents) {
          // New guest is the pending webview
          event.newGuest = nextContents;
          nextContents = null;
          // Make a new one when we can
          mainWindow.webContents.send('webview-used');
        }
      });
    }
    
    openNewWindowsInWebView(
      webContents.fromId(idOfWebViewWindowOpenIsCalledFrom
    );

    As mentioned before this code is 100% untested and can probably be cleaned up / be better but it should give you enough of an idea around the architecture to get something working

  10. Gozala commented on Oct 10, 2018

    @Gozala
    Author

    Thanks for the webvie prealocation idea it seens clever way to ensure webcontents are there for when open occurs.

    Unfortunately turns out there is another issue, of new-window events not being dispatched if they originated from within document inside webview 😂

    @MarshallOfSound Should I create separate issue for that or keep gourmet here ?

  11. MarshallOfSound commented on Oct 10, 2018

    @MarshallOfSound
    Member

    @Gozala We have open issues tracking window.open not working quite right for iframes.

    #9581
    #10401
    #9973

  12. Gozala commented on Oct 10, 2018

    @Gozala
    Author

    I did some debugging and as far as I understand this is a reason why 'new-window' on main isn't dispatched

    event.sender.emit('new-window', event, url, frameName, disposition, options, additionalFeatures, referrer)
    const { newGuest } = event
    if ((event.sender.isGuest() && !event.sender.allowPopups) || event.defaultPrevented) {
    if (newGuest != null) {
    if (options.webContents === newGuest.webContents) {
    // the webContents is not changed, so set defaultPrevented to false to
    // stop the callers of this event from destroying the webContents.
    event.defaultPrevented = false
    }
    event.returnValue = setupGuest(event.sender, frameName, newGuest, options)
    } else {
    event.returnValue = null

    As far as I can tell event.sender.emit('new-window', ...) will result in an async message send to renderrer process, but given that it's async newGuest on next line will always be falsy and there for setupGuest will never happen.

  13. Gozala commented on Oct 10, 2018

    @Gozala
    Author

    It seems to me that either:

    • Instead of doing event.sender.emit('new-window', ... code there supposed to emit that on the webContents of the corresponding BrowserWindow. In which case it would be able to setup the newGuest corresponding to pre-allocated webview.
    • Or message should be send to renderrer host instead which could then forward it onto either main process or assign corresponding guestId itself.

    Later seems more intuitive but then it also appears that to me that sending sync message to renderrer host seems to block client blocked.

  14. MarshallOfSound commented on Oct 10, 2018

    @MarshallOfSound
    Member

    As far as I can tell event.sender.emit('new-window', ...) will result in an async message send to renderrer process

    This is incorrect, event.sender.emit will emit an event syncronously on the webContents in the main process. event.sender.send would send an IPC event.

  15. Gozala commented on Oct 10, 2018

    @Gozala
    Author

    I've put together an example that follows the idea of prealocated web-views:

    https://github.com/Gozala/electron-quick-start/blob/915bb3b900343039639d0fa4ef22bb59a224c843/main.js#L92-L99

    Although as per my last comment since guest-window-manager.js wrongly assumes that newGuest will be set by 'new-window' event handler, I had to substitute default implementation with one that does not has that assumption:

    https://github.com/Gozala/electron-quick-start/blob/915bb3b900343039639d0fa4ef22bb59a224c843/main.js#L101-L103

    Example seems to work in that document calling window.open() does get WindowProxy and is able to exchange messages with it.

    Unfortunately window being opened does not seem to get window.opener setup though, that is because parentId passed to window-setup is undefined:

    require('@electron/internal/renderer/window-setup')(ipcRenderer, guestInstanceId, openerId, hiddenPage, usesNativeWindowOpen)

    That is as far as I can tell is because <webview webpreferences="openerId=20" /> does not seem to end up in the webPreferences for the corresponding webContenst.

    } else if (arg.indexOf('--opener-id=') === 0) {
    // This is a guest BrowserWindow.
    process.openerId = parseInt(arg.substr(arg.indexOf('=') + 1))

    Also searching through the source I don't seem to get much on openerId so I'm not sure how to make it pass it on.

  16. Gozala commented on Oct 12, 2018

    @Gozala
    Author

    @MarshallOfSound So given the findings from my previous comment what do you suggest to do here ? Would it make sense to do what I suggested (quoting below for convenience):

    Instead of doing event.sender.emit('new-window', ... code there supposed to emit that on the webContents of the corresponding BrowserWindow. In which case it would be able to setup the newGuest corresponding to pre-allocated webview.

    Alternatively event other than new-window eg new-webview-window could be dispatched in main process. If that event ends up being prevented then skip calling event.sender.emit('new-window', ... otherwise do that.

  17. ryanflowers commented on Jan 25, 2019

    @ryanflowers

    @Gozala I am looking to do something very similar to you. I am trying to take the web contents from window.open issued within a webview(webview A) and show it in another webview(webview B) on the page.

    I tried out your POC and the 'new-window' event doesnt seem to get fired when executing native window open within a webview. Were you ever able to get this to work? I tried the code here https://github.com/Gozala/electron-quick-start/blob/915bb3b900343039639d0fa4ef22bb59a224c843/main.js#L101-L103

  18. Gozala commented on Jan 25, 2019

    @Gozala
    Author

    @ryanflowers It’s being a while now, but if I recall correctly it only worked for non native as the native was taking completely different code path. I do remember for sure that it only worked in some combination of prefs and not the other

  19. ryanflowers commented on Jan 28, 2019

    @ryanflowers

    @Gozala I have found that you actually need to listen on the 'web-contents-created' event to wire up the 'new-window' event and it will fire.

      webContents.on(
        "new-window",
        (event, url, frameName, disposition, options, additionalFeatures) => {
    

    One more question.. did you ever find a way to actually get the webContents resulting from the window.open to be embedded in the webview on the page? I looked through your branches and I dont see this was successful.

    Thank you for any info you may have!

  20. Gozala commented on Jan 28, 2019

    @Gozala
    Author

    One more question.. did you ever find a way to actually get the webContents resulting from the window.open to be embedded in the webview on the page? I looked through your branches and I dont see this was successful.

    I'm not sure I understand the question. What I was aiming to do is have window.open(...).postMessage({ ping: 1 }) working, and back & I got it to work. That being said I don't really remember all the hacks / prefs I had to do to make it work. It also could be that things have changed on Electron side since & my PoC no longer works.

    I also have not end up using any of that as even though it worked I could not convince Beaker to adopt the hack so I just end up giving up on it, which is also why I can't remember details.

  21. sgd2z commented on Aug 21, 2020

    @sgd2z
    Contributor

    @Gozala Full disclosure, never done this before and code I write here is untested 😆 Before I run through this using a webview it's worth noting you'll have a way better time using a BrowserView based architecture.

    Now let's try this, so in order to "open" a new window into a webview we need a few things.

    1. As you noted, window.open is synchronous and blocking meaning we can't ask the renderer to make us a new webview, that means we need a webview ready and waiting to receive an "opened" window.
    2. We need to do all this work in the main process because as previously noted event.preventDefault() and event.newGuest must be called / assigned synchronously when the event is initially emitter.

    Solving (1) is quite straightforward, we just have an empty webview element laying around all the time, as soon as it is used you make a new one. I.e.

    <webview src="about:blank" />
    <script>
    const { ipcRenderer } = require('electron');
    
    ipcRenderer.on('webview-used', () => {
      const webview = document.createElement('webview');
      webview.setAttribute('src', 'about:blank');
      document.body.appendChild(webview);
    });
    </script>
    

    Then in the main process we just need to keep a reference to the webContents of this "ready" webview.

    // Main Process
    let nextContents = null;
    
    mainWindow.webContents.on('did-attach-webview', (event, webContents) => {
      if (webContents.getURL() === 'about:blank') {
        nextContents = webContents;
      }
    });

    Now we have a pending webContents and a way to make new ones we just need to correctly intercept the window.open calls in the main process to solve (2).

    // Main Process
    function openNewWindowsInWebView (webContents) {
      webContents.on('new-window', (event) => {
        event.preventDefault();
        if (nextContents) {
          // New guest is the pending webview
          event.newGuest = nextContents;
          nextContents = null;
          // Make a new one when we can
          mainWindow.webContents.send('webview-used');
        }
      });
    }
    
    openNewWindowsInWebView(
      webContents.fromId(idOfWebViewWindowOpenIsCalledFrom
    );

    As mentioned before this code is 100% untested and can probably be cleaned up / be better but it should give you enough of an idea around the architecture to get something working

    Hi @MarshallOfSound - how would one do this with a BrowserView based architecture as you propose?

  22. lucasbaze commented on Aug 27, 2020

    @lucasbaze

    I second @sgd2z's question @MarshallOfSound . Curious on the same thing. Been having trouble with capturing new-window events from a BrowserView in the BrowserWindow.

    Currently trying to capture the following unsuccessfully:

    // main.js
    mainWindow = new BrowserWindow(...);
    mainWindow.loadUrl(...);
    
    mainWindow.webContents.on('new-window', (e, url, frameName, disposition) => {
      e.preventDefault();
     });
    
    // renderer.js
    
    this.view = new remote.BrowserView(...);
    
    // I know this doesn't work
    this.view.webContents.on('new-window', (e, ..args) => {
       e.preventDefault();
    }
    

    Basically if there was a code example of #2770 (comment) that would be fantastic.

  23. asd281533890 commented on Aug 29, 2022

    @asd281533890

    I found a browser called 想天浏览器 developed by Electron in China. Using window.open, it can return to windowProxy normally, and the opened webpage can also visit window.opener normally. I don't know the specific implementation details, and I don't know whether the web page is implemented using browserview or webview.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions