【问题标题】:load and execute a script in android and ios在 android 和 ios 中加载并执行脚本
【发布时间】:2018-01-31 22:12:24
【问题描述】:

我的要求:

  • 这应该适用于 Android 和 iOS
  • 我想从文件(不一定通过网络)加载脚本(可以是 Javascript 或 Lua 或任何其他脚本语言)
  • 脚本应该在后台线程中运行,并且能够发布到 UI 线程
  • 我想在 iOS 和 Android 中使用相同的脚本,以便我可以在 Android 和 iOS 应用程序中重复使用脚本代码

我有哪些选择?

【问题讨论】:

    标签: javascript android ios lua


    【解决方案1】:

    WebView Android 启用了 Javascript

    我认为 iOS 中的 SFWebView 也支持 Javascript。

    不确定是否可以在后台线程中使用它,因为 Android Webview 只会在 UI 线程上运行

    【讨论】:

    • 我希望不用 WebView。还是谢谢。
    【解决方案2】:

    回答: 1. 您必须将 HTML 加载到字符串中:

    private String readHtml(String remoteUrl) {
    String out = "";
    BufferedReader in = null;
    try {
        URL url = new URL(remoteUrl);
        in = new BufferedReader(new InputStreamReader(url.openStream()));
        String str;
        while ((str = in.readLine()) != null) {
            out += str;
        }
    } catch (MalformedURLException e) { 
    } catch (IOException e) { 
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return out;
    }
    
    1. 使用基本 URL 加载 WebView:

       String html = readHtml("Your Web URL");
       mWebView.loadDataWithBaseURL("file:///android_asset/", html, "text/html", "utf-8", "");
      

    在这种特殊情况下,您应该将要在页面上使用的所有 .js 文件保存在项目的“assets”文件夹下的某个位置。例如:

     /MyProject/assets/jquery.min.js
    
    1. 在您的远程 html 页面中,您必须加载驻留在应用程序中的 .js 和 .css 文件,例如:

    这同样适用于所有其他本地资源,如图像等。它们的路径必须以开始

    file:///android_asset/
    

    WebView 将首先加载您作为字符串提供的原始 HTML,然后选择 .js、.css 和其他本地资源,然后加载远程内容。

    【讨论】:

    • 我希望不用 WebView。还是谢谢。
    【解决方案3】:

    在 android 中,将页面加载到 webview 中时。拦截脚本调用。

    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
     if ( url.endsWith("script.js") ) {
        AssetFileDescriptor fileDescriptor = assetManager.openFd("script.js");
        FileInputStream stream = fileDescriptor.createInputStream();
        return new WebResourceResponse("text/javascript","UTF-8",stream);
     }
    }
    

    Webview 在 ui 线程上运行。我不确定是否有办法从后台线程加载网络资源。

    【讨论】:

    • 我希望不用 WebView。无论如何,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-28
    • 2021-02-18
    • 2017-08-23
    相关资源
    最近更新 更多