下载由android webview中的javascript生成的文件 [英] Download file generated by javascript in android webview

查看:143
本文介绍了下载由android webview中的javascript生成的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有网络视图的android应用.

I have an android app with a webview.

每当用户单击按钮时,JavaScript都会创建一个Blob,将其放入文本中并下载.

Whenever a user clicks on a button, JavaScript creates a blob, puts text in it and downloads it.

这是执行此操作的功能:

Here's the function that does this:

function saveTextAsFile(A)
{
    FillTextToWrite(A);
    var textFileAsBlob = new Blob([textToWrite], {
        type: 'text/plain'
    });
    var downloadLink = document.createElement("a");
    downloadLink.download = "Analysis.txt";
    downloadLink.innerHTML = "Download File";
    if (window.webkitURL != null)
    {
        downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
    }
    else
    {
        downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
        downloadLink.onclick = destroyClickedElement;
        downloadLink.style.display = "none";
        document.body.appendChild(downloadLink);
    }

    downloadLink.click();
}

它在任何浏览器中都可以正常工作,但是当我尝试在应用中下载它时,什么也没发生.

It works fine in any browser, but when I try to download it in the app, nothing happens.

是否可以在应用程序中下载Blob,或者更容易更改JavaScript?

Is there a way to download the blob in the app or is it easier to change the JavaScript?

我需要JavaScript才能在浏览器以及android应用程序上运行,因此将blob发送到JavaScript中的android应用程序将无法在浏览器上运行.

I need the JavaScript to work on browser as well as on the android app, so sending the blob to the android app in JavaScript will not work on browser.

推荐答案

我发现的解决方案是检测JavaScript是否在Android应用程序或浏览器中运行(通过向用户代理添加字符串).

The solution I found was to detect wheter the javascript is running in Android app or in browser (by adding a string to the user agent).

在Android应用中,我正在向Java发送变量 textToWrite (通常会进入blob).

When in Android app I am sending variable textToWrite (which would normally go into the blob) to the java.

在javascript中

In javascript:

if(App){
    Android.sendData(textToWrite);
} else {//make blob}

在Java中:

myWebView.addJavascriptInterface(new myJavascriptInterface(this), "Android");

public class myJavascriptInterface {
    Context mContext;

    myJavascriptInterface(Context c) {
        mContext = c;
    }

    @JavascriptInterface
    public void sendData(String data) {
        //save data as file
    }
}

这篇关于下载由android webview中的javascript生成的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆