我正在构建一个使用 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);
}
}