简体   繁体   English

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

[英]How can you add mutation observer to a WebView2 control

I'm building a WinForms App that is using WebView2 control Is there an a way to inject some JavaScript maybe with a mutation observer to get the content of a div after an ajax call?我正在构建一个使用 WebView2 控件的 WinForms 应用程序有没有办法在 ajax 调用后注入一些 JavaScript 可能与变异观察者获取 div 的内容?

I think this could be done using ScriptNotify in WebVeiw我认为这可以在 WebVeiw 中使用 ScriptNotify 来完成

My problem is I can inject a script but the control is returned back to WinForms before the JavaScript finishes我的问题是我可以注入脚本,但在 JavaScript 完成之前控制权返回到 WinForms

C# 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

// 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);
    }
}

Calling await on an ExecuteScriptAsync call will wait for the synchronous global script to execute or throw an unhandled exception.在 ExecuteScriptAsync 调用上调用 await 将等待同步全局脚本执行或引发未处理的异常。 So any asynchronous JavaScript code like callbacks from setTimeout, promises, or a MutationObserver, will not be awaited by ExecuteScriptAsync.因此,ExecuteScriptAsync 不会等待任何异步 JavaScript 代码,例如来自 setTimeout、promises 或 MutationObserver 的回调。 Or if there's any unhandled exception it will stop executing the injected script.或者,如果有任何未处理的异常,它将停止执行注入的脚本。

If you need to know about asynchronous JavaScript code completing, you can use CoreWebView2.WebMessageReceived and chrome.webview.postMessage to send a message from your script to your native code once the script is done.如果您需要了解异步 JavaScript 代码完成,您可以使用CoreWebView2.WebMessageReceivedchrome.webview.postMessage在脚本完成后将消息从您的脚本发送到您的本机代码。

If you want detailed error information in the case of an unhandled exception you can wrap your injected code in a try/catch block and examine any unhandled exceptions.如果您想在未处理的异常情况下获得详细的错误信息,您可以将注入的代码包装在 try/catch 块中并检查任何未处理的异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM