如何在WebView2中以文本形式读取BLOB中的数据?我尝试过从Javascript中调用WebView2,但我无法让它正常工作。我理解它是否是Javascript解决方案,但我更喜欢C++。
发布于 2020-09-02 07:45:50
不幸的是,Webview2不支持异步函数导致了ExecuteScript。我通过使用ajax执行同步请求来获得数据。
wstring jquery(L"var jqry = document.createElement('script');"
L"jqry.src = 'https://code.jquery.com/jquery-3.3.1.min.js';"
L"document.getElementsByTagName('head')[0].appendChild(jqry);");
webview->ExecuteScript(jquery.c_str(), Callback<ICoreWebView2ExecuteScriptCompletedHandler>(
[](HRESULT errorCode, PCWSTR result) -> HRESULT {
return S_OK;
}).Get());
Sleep(500);
wstring script(L"jQuery.noConflict();"
L"function testAjax() {"
L"var result='';"
L"jQuery.ajax({"
L"url:document.getElementById('test').href,"
L"async: false,"
L"success:function(data) {"
L"result = data; "
L"}"
L"});"
L"return result;"
L"}"
L"(() => {"
L"return testAjax()"
L"})();");
webview->ExecuteScript(script.c_str(), Callback<ICoreWebView2ExecuteScriptCompletedHandler>(
[](HRESULT errorCode, LPCWSTR result) -> HRESULT {
wprintf(L"%ls\n", result);
return S_OK;
}).Get());但是同步调用在执行时阻塞web代码。这是不推荐的,但这对我的情况是可以的。如果你正在寻找另一种方式而不阻塞网络代码,那么将文本发回本地可能是一个更好的主意,如@David建议的。
发布于 2020-08-27 17:02:55
WebView2没有提供与Blobs交互的机制。您可以在脚本中把小块变成文字,然后使用window.chrome.webview.postMessage方法和WebMessageReceived事件将文本回发到本机端。
如果这对您不起作用,您可以在WebView2反馈GitHub项目上提出一个特性请求。
async function example() {
function textToBlob(text) {
return new Blob([text], {type : 'text/plain'});
}
async function blobToText(blob) {
return (new Response(blob)).text();
}
const blob = textToBlob("example");
const text = await blobToText(blob);
alert(text);
}
example();
https://stackoverflow.com/questions/63610311
复制相似问题