Search code examples
visual-c++popupwindowwebview2

Displaying the same webpage in a popup window using WebView2?


MFC, Win32, VC++

Code:

if (m_pImpl->m_webView)
{
    m_pImpl->m_webView->ExecuteScript(L"window.open(url)",
        Callback<ICoreWebView2ExecuteScriptCompletedHandler>(
            [](HRESULT error, PCWSTR result) -> HRESULT { return S_OK; })
        .Get());
}

If I use window.print() the JavaScript executes and I see a print dialog. So I know it is working. But nothing happens when I use window.open(url). Why? I have not disabled popups.

Even the official Sample App won't display the page in a popup window when using its Execute Script feature.


I should clarify m_webView:

wil::com_ptr<ICoreWebView2> m_webView;

Update

Part of the issue is that using url is wrong. If I use 'https://www.microsoft.com' it works.

But I am trying to open a local html file on my local driver.


Solution

  • Step 1

    CString CWebBrowser::GetLocationURL()
    {
        CString url;
        if (m_pImpl->m_webView)
        {
            wil::unique_cotaskmem_string uri;
            m_pImpl->m_webView->get_Source(&uri);
    
            if (wcscmp(uri.get(), L"about:blank") == 0)
            {
                uri = wil::make_cotaskmem_string(L"");
            }
    
            url = uri.get();
        }
    
        return url;
    }
    

    Step 2

    void CWebBrowser::ShowPrintUIFullScreen(const CString strUrl)
    {
        if (m_pImpl->m_webView)
        {
            m_pImpl->m_webView->ExecuteScript(L"window.open('" + GetLocationURL() + L"')",
                Callback<ICoreWebView2ExecuteScriptCompletedHandler>(
                    [](HRESULT error, PCWSTR result) -> HRESULT { return S_OK; })
                .Get());
        }
    }
    

    Works like a charm!