Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to cast to Microsoft.Web.WebView2.Core.Raw.ICoreWebView2Environment during initialization. #1676

Closed
ODtian opened this issue Aug 21, 2021 · 1 comment
Labels
bug Something isn't working

Comments

@ODtian
Copy link

ODtian commented Aug 21, 2021

Description

I have been trying to use pythonnet and wpf mixed programming and start a webview2 in wpf, refer to pywebview. Unfortunately, I encountered the following problem during initialization:

Unable to cast to Microsoft.Web.WebView2.Core.Raw.ICoreWebView2Environment.
This may happen if you are using an interface not supported by the version of the WebView2 Runtime you are using.
For instance, if you are using an experimental interface from an older SDK that has been modified or removed in a newer runtime.
Or, if you are using a public interface from a newer SDK that wasn't implemented in an older runtime.
For more information about WebView2 versioning please visit the following: https://docs.microsoft.com/microsoft-edge/webview2/concepts/versioning
   在 Microsoft.Web.WebView2.Core.CoreWebView2Environment.get__nativeICoreWebView2Environment()
   在 Microsoft.Web.WebView2.Core.CoreWebView2Environment.<CreateCoreWebView2ControllerAsync>d__41.MoveNext()
--- 引发异常的上一位置中堆栈跟踪的末尾 ---
   在 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   在 Microsoft.Web.WebView2.Wpf.WebView2.<>c__DisplayClass26_0.<<EnsureCoreWebView2Async>g__Init|0>d.MoveNext()

I've seen issus #730 and it helps me load WebView2Loader.dll correctly.
More addtion, Microsoft.Web.WebView2.Core.Raw.ICoreWebView2Environment could be found and imported correctly in python.

Version
SDK: 1.0.864.35, 1.0.902.49 and 1.0.955-prerelease, same the issue.
Runtime: 92.0.902.78
Framework: WPF
OS: Win10

Repro Steps

import os
import sys

import clr

# To add WebView2Loader.dll to the path. Therefore webview runtime could be loaded.
os.environ["Path"] = (
    os.path.abspath("./x64")
    + ";"
    + os.environ["Path"]
)

clr.AddReference("wpf/PresentationFramework")
clr.AddReference("System.Drawing")
clr.AddReference(
    os.path.abspath(
        "./Microsoft.Web.WebView2.Core.dll"
    )
)
clr.AddReference(
    os.path.abspath(
        "./Microsoft.Web.WebView2.Wpf.dll"
    )
)

from Microsoft.Web.WebView2.Core import CoreWebView2Environment, Raw
from Microsoft.Web.WebView2.Wpf import CoreWebView2CreationProperties, WebView2

from System import Uri, Func, Type
from System.Drawing import Color, ColorTranslator, Icon, Point, Size, SizeF
from System.IO import StreamReader
from System.Threading import ApartmentState, Thread, ThreadStart
from System.Windows import Application, LogicalTreeHelper, Window
from System.Windows.Controls import Label
from System.Windows.Markup import XamlReader

import time

xaml = """
<Window 
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
       Title="WpfApplication1" Height="300" Width="300"
       >
    <Grid Name="Grid">
    </Grid>
</Window> 
"""


class MyWindow(Window):
    def __init__(self):
        window = XamlReader.Parse(xaml)
        web_view = WebView2()
        props = CoreWebView2CreationProperties()
        props.UserDataFolder = os.path.join(os.environ["LOCALAPPDATA"], "pywebview")
        web_view.CreationProperties = props
        web_view.CoreWebView2InitializationCompleted += self.on_webview_ready
        web_view.Source = Uri("https://bing.com")
        grid = LogicalTreeHelper.FindLogicalNode(window, "Grid")
        grid.Children.Add(web_view)
        app = Application()
        app.Run(window)

    def on_webview_ready(self, sender, args):
        print(args.InitializationException)
 
        def _():
            print("webview ready")
            try:
                settings = sender.CoreWebView2.Settings
                settings.AreDefaultContextMenusEnabled = True
                settings.AreDefaultScriptDialogsEnabled = True
                settings.AreDevToolsEnabled = True
                settings.IsBuiltInErrorPageEnabled = True
                settings.IsScriptEnabled = True
                settings.IsWebMessageEnabled = True
                settings.IsStatusBarEnabled = True
                settings.IsZoomControlEnabled = True
            except Exception as e:
                print(e)

        try:
            sender.Dispatcher.Invoke(Func[Type](_))
        except Exception as e:
            print(e)

if __name__ == "__main__":
    def _create2():
        MyWindow()

    thread = Thread(ThreadStart(_create2))
    thread.SetApartmentState(ApartmentState.STA)
    thread.Start()
    thread.Join()

I used above code to start wpf and got / print the error at method on_webview_ready.

Screenshots

Additional context
I've found a same issue (using C#) which can't be found anywhere apart from githubmemory.com
https://githubmemory.com/repo/MicrosoftEdge/WebView2Feedback/issues/1577
(Web page badly load somehow, I could see it through google snapshot)

@ODtian ODtian added the bug Something isn't working label Aug 21, 2021
@ODtian
Copy link
Author

ODtian commented Aug 22, 2021

found at #1577

@ODtian ODtian closed this as completed Oct 30, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant