[英]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.WebMessageReceived
和chrome.webview.postMessage
在腳本完成后將消息從您的腳本發送到您的本機代碼。
如果您想在未處理的異常情況下獲得詳細的錯誤信息,您可以將注入的代碼包裝在 try/catch 塊中並檢查任何未處理的異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.