WebView2-如何从BLOB URL读取数据?

问题描述

我如何从WebView2的BLOB Url中以文本形式读取数据?我已经尝试过Javascript的WebView2回调,但我无法使其正常工作。我很欣赏这是否是Javascript解决方案,但我更喜欢C ++。

解决方法

WebView2不提供与Blob交互的机制。您可以在脚本中turn the Blob into text,然后使用window.chrome.webview.postMessage方法和WebMessageReceived event将文本发布回本地。

如果这对您不起作用,则可以在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();

,

不幸的是,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(),LPCWSTR result) -> HRESULT {
        wprintf(L"%ls\n",result);

    return S_OK;
}).Get());

但是同步调用会在执行时阻止Web代码。不建议这样做,但是对于我的情况是可以的。如果您正在寻找另一种方法而又不阻止Web代码,则将文本发回到本机端可能是一个更好的主意,如@David Risney建议的那样。