如何将突变观察器添加到 WebView2 控件

How can you add mutation observer to a WebView2 control

我正在构建一个使用 WebView2 控件的 WinForms 应用程序 有没有一种方法可以在 ajax 调用后用突变观察器注入一些 JavaScript 来获取 div 的内容?

我认为这可以在 WebVeiw 中使用 ScriptNotify 来完成

我的问题是我可以注入脚本,但控制权在 JavaScript 完成之前返回到 WinForms

C#

        private async void webView21_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e)
    {
        StatusLabel.Text = "Page loaded";
       string Script = File.ReadAllText(@"D:\Vb\Test\WebView2ControlWinForms\TestScript.js");

        await webView21.CoreWebView2.ExecuteScriptAsync(Script);

        // Stop here until last line finishesd;
        string res = await webView21.CoreWebView2.ExecuteScriptAsync(@"document.getElementById('res').innerHTML");
        var htmldecoded = System.Web.Helpers.Json.Decode(res);
        richTextBox1.Text = htmldecoded;
    }

JavaScript

// JavaScript source code
var results = [];
let target = document.querySelector('.getblock')
let config = { childList: true }
let observer = new MutationObserver(function (mutationList, observer) {
    console.log("CONTENT CHANGED!")
    console.log(mutationList)
    console.log(observer)
    for (const mutation of mutationList) {
        if (mutation.type === 'childList') {
            console.log('A child node has been added or removed.');
            results.push(mutation);
        }
        else if (mutation.type === 'attributes') {
            console.log('The ' + mutation.attributeName + ' attribute was modified.');
        }
    }
    //json = JSON.stringify(results);
    //returnFunc(json);

    GetLinks();
    
})

observer.observe(target, config)

var el = document.querySelectorAll('.getblock span');
//var el = document.querySelectorAll('button');
var i;
alert("el is " + el.length + " Long");
for (i = 0; i < el.length; i++) {
    // alert("Click "+ i);
    el[i].click();
}

function GetLinks() {
    alert("Hello from GetLinks ")
    var el = document.querySelectorAll('.getblock  a');
    alert("Hello from GetLinks " + el.length);
    var i;
    var json;
    for (i = 0; i < el.length; i++) {
        results.push(el[i].href);
        json = JSON.stringify(results);
    }
    returnFunc(json);
}

function returnFunc(json) {
    var ele = document.getElementById('res');
    if (ele !== null) {
        ele.innerHTML = json
    } else {
        var div = document.createElement('div');
        div.id = 'res';
        div.innerHTML = json
        document.body.appendChild(div);
    }
}

在 ExecuteScriptAsync 调用上调用 await 将等待同步全局脚本执行或引发未处理的异常。因此,ExecuteScriptAsync 不会等待任何异步 JavaScript 代码,例如来自 setTimeout、promises 或 MutationObserver 的回调。或者,如果有任何未处理的异常,它将停止执行注入的脚本。

如果您需要了解异步 JavaScript 代码完成,您可以使用 CoreWebView2.WebMessageReceivedchrome.webview.postMessage 在脚本完成后将消息从脚本发送到本机代码.

如果您想在未处理的异常情况下获得详细的错误信息,您可以将注入的代码包装在 try/catch 块中并检查任何未处理的异常。