How do i read data as text from a BLOB Url in WebView2 ? I've tried WebView2 callback from Javascript which i couldn't make it work. I appreciate whether it is a Javascript solution or not but i prefer C++.
Asked
Active
Viewed 1,017 times
2 Answers
1
WebView2 doesn't provide a mechanism to interact with Blobs. You can turn the Blob into text in script and then post the text back to the native side with the window.chrome.webview.postMessage
method and the WebMessageReceived event.
If this doesn't work for you, you can make a feature request on the WebView2 Feedback GitHub Project.
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();

David Risney
- 3,886
- 15
- 16
-
I need to make this a returning function. And it is always returning as pending response with empty result, never fulfilled. It seems to be working fine when you alert the text or console.log but i couldn't figure it out. How do you make a returning function? Can you show me a working example with `public HRESULT ExecuteScript(LPCWSTR javaScript,ICoreWebView2ExecuteScriptCompletedHandler * handler)` – Kitiara Aug 28 '20 at 17:18
-
Oh I see. The JavaScript needs to be async but ExecuteScript doesn't wait for async script to complete. To get the result of async JavaScript, you could use ExecuteScript to inject the script and then use chrome.webview.postMessage to send the result back to the native side's CoreWebView2.WebMessageReceived event. – David Risney Sep 04 '20 at 18:26
1
Unfortunately, Webview2 doesn't support async function results in ExecuteScript. I managed to get data by performing synchronous request with 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());
But synchronous calls block the web code while executing. This is not recommended, but it is ok for my case. If you are looking for another way without blocking the web code, posting the text back to the native side maybe a better idea as @David Risney suggested.

Kitiara
- 343
- 6
- 21