简体   繁体   中英

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?

I think this could be done using ScriptNotify in WebVeiw

My problem is I can inject a script but the control is returned back to WinForms before the JavaScript finishes

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

Calling await on an ExecuteScriptAsync call will wait for the synchronous global script to execute or throw an unhandled exception. So any asynchronous JavaScript code like callbacks from setTimeout, promises, or a MutationObserver, will not be awaited by ExecuteScriptAsync. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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