如何将变异观察者添加到WebView2控件

问题描述

我正在构建一个使用WebView2控件的WinForms应用程序 是否有一种方法可以通过突变观察器注入一些JavaScript,以在ajax调用获取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,promise或MutationObserver的回调。或者,如果有任何未处理的异常,它将停止执行注入的脚本。

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

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