Access WebView2 newly opened window

6k views Asked by At

If I run window.open("url") it will open url in new popup window, even if it is Edge WebView2. It will just have default Windows title-bar, and read-only url bar. I need to open url from WebView exactly in new popup window, via window.open("url").

Is there any way to access that window from my program as far as original WebView2 child-window? By accessing I mean injecting scripts, and getting js-response after injecting.

Or, at least, perhaps there is way to open url with some pre-injected script, like window.open("http://google.com -javascript: alert(5)")?


Update

Found MSDN article, probably this is what do I need. Trying to understand that.

1

There are 1 answers

4
David Risney On

Yes, the ICoreWebView2::add_NewWindowRequested event lets you intercept WebView2 opening new windows.

If you do nothing in the event handler, or don't subscribe to the event, you'll get a new popup like you describe. In script the return value of window.open is connected up to the newly opened popup window. But in your native code you have no access to or control over the newly opened window.

Or you can set the Handled property to true on the NewWindowRequested event's args, and no new window will be created. This is useful if you want to prevent opening windows or if you want to send new window opens to the default browser or somewhere else. In script the return value of window.open is null.

Or you can provide your own ICoreWebView2 via the NewWindow property. In this case you are responsible for and get to choose how to host that ICoreWebView2 in some manner. The ICoreWebView2 you provide as the NewWindow will be the target of the new window navigation and connected back up via script to the return value of the window.open call.

Because obtaining a new WebView2 may require asynchronous method calls, you can use the GetDeferral method on the event args to stop the completion of the window requested event until you call Complete on the deferral asynchronously later.

You can see a working sample of the add_NewWindowRequested event in our sample app.