25

アプリのリソース フォルダーから JavaScript ファイルを読み込む必要があります。現時点では、リソースから画像を正常に読み取りますが、何らかの理由で JavaScript を読み取っていません。

html ファイル自体がリソースに書き込まれている場合、これらの JavaScript を参照する html ドキュメントをレンダリングできましたが、UIWebView の html を動的に設定して html/js をレンダリングしたいと考えています。

これが私がやっていることです:

NSString * html = @"<!DOCTYPE html><html><head><title>MathJax</title></head><body><script type=\"text/x-mathjax-config\">MathJax.Hub.Config({tex2jax: {inlineMath: [[\"$\",\"$\"],[\"\\(\",\"\\)\"]]}});</script><script type=\"text/javascript\" src=\"/MathJax/MathJax.js\"></script>$$\\int_x^y f(x) dx$$<img src=\"coffee.png\"></body></html>";

NSString * path = [[NSBundle mainBundle] resourcePath]; 
path = [path stringByReplacingOccurrencesOfString:@"/" withString:@"//"];
path = [path stringByReplacingOccurrencesOfString:@" " withString:@"%20"];

NSString * resourcesPath = [[NSString alloc] initWithFormat:@"file://%@/", path];
[webview loadHTMLString:html baseURL:[NSURL URLWithString:resourcesPath]];

ここで、必要なファイルもあるサーバーにベース URL を変更すると、正しく読み込まれます。インターネット接続を必要としないのは素晴らしいことです。どんな助けでも大歓迎です!!! ;)

これは、画像を表示するのに役立つことがわかりました: iPhone Dev: UIWebView baseUrl to resources in Documents folder not App bundle

編集:

文字列の置換と URL のエンコードを行う代わりに、mainBundle で resourceURL を呼び出すだけで画像を取得できましたが、JavaScript は実行されませんでした。

    NSString * setHtml = @"<!DOCTYPE html><html><head><title>MathJax</title></head><body><script type=\"text/x-mathjax-config\">MathJax.Hub.Config({tex2jax: {inlineMath: [[\"$\",\"$\"],[\"\\(\",\"\\)\"]]}});</script><script type=\"text/javascript\" src=\"/MathJax/MathJax.js\"></script>$$\\int_x^y f(x) dx$$<img src=\"images/test.png\"></body></html>";
    [webview loadHTMLString:setHtml baseURL:[[NSBundle mainBundle] resourceURL]];

編集

これを試してみたい場合は、サンプル プロジェクトを作成することで簡単にできます。

https://github.com/pyration/math-test

git clone git@github.com:pyramation/math-test.git
4

5 に答える 5

50

ここでは、簡単な設定を行います。

Resources フォルダーに次のフォルダー構造を作成します。

青いフォルダは参照されていることに注意してください

ここに画像の説明を入力

CSSはただのキャンディーです:) lib.jsには、使用したいJavaScriptコードがあります。

index.html

<html>
    <head>
        <link rel="stylesheet" type="text/css" href="css/standard.css">

        <script src="js/lib.js" type="text/javascript" />
    </head>
    <body>
        <h2>Local Javascript</h2>

        <a href="javascript:alert('Works!')">Test Javascript Alert</a>      

        <br/>
        <br/>

        <a href="javascript:alertMeWithMyCustomFunction('I am');">External js test</a>
    </body>
</html>

lib.js

function alertMeWithMyCustomFunction(text) {
    alert(text+' -> in lib.js');
}

webview でのコンテンツの読み込み

注: webView はプロパティであり、インスタンス ビルダーで作成されたビュー

- (void)viewDidLoad
{   
    NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"index" 
                                                         ofType:@"html" 
                                                    inDirectory:@"/htdocs" ];

    NSString *html = [NSString stringWithContentsOfFile:htmlPath 
                                               encoding:NSUTF8StringEncoding 
                                                  error:nil];

    [webView loadHTMLString:html 
                    baseURL:[NSURL fileURLWithPath:
                             [NSString stringWithFormat:@"%@/htdocs/", 
                             [[NSBundle mainBundle] bundlePath]]]];
}

そして、これは結果になるはずです:

ここに画像の説明を入力 ここに画像の説明を入力

編集:

snowman4415 は、iOS 7 はスクリプト タグの自己終了タグを好まないため、iOS 7 で何かが機能しない場合は、タグを閉じる必要があるかもしれないと述べました。</script>

于 2011-04-27T21:38:25.730 に答える
16

ローカルの JavaScript ファイルを Web ビューの DOM に挿入する別の方法を次に示します。JS ファイルの内容を文字列にロードしてから、次を使用しますstringByEvalutatingJavaScriptFromString

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSString *jsFile = @"jquery-1.8.2.min.js";
    NSString *jsFilePath = [[NSBundle mainBundle] pathForResource:jsFile ofType:nil];
    NSURL *jsURL = [NSURL fileURLWithPath:jsFilePath];
    NSString *javascriptCode = [NSString stringWithContentsOfFile:jsURL.path encoding:NSUTF8StringEncoding error:nil];
    [webView stringByEvaluatingJavaScriptFromString:javascriptCode];
    // ...
}

これは、表示している *.html/xhtml ファイル (ePub リーダーやニュース アグリゲーターなど) を所有していない場合に特に便利です。xhtml ファイルから js ファイルへの相対パスを気にする必要がなくなるので便利です。

于 2012-11-20T12:44:59.267 に答える
3

これは、Webview とローカル JS を使用した方法です。ここにいくつかのスナップショットを入れて、ここにサンプル プロジェクトを置きます

資力

// Get the path for index.html, where in which index.html has reference to the js files, since we are loading from the proper resource path, the JS files also gets picked up properly from the resource path.

func loadWebView(){

    if let resourceUrl = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "WebDocs2"){
        let urlRequest = URLRequest.init(url: resourceUrl)
        myWebView.loadRequest(urlRequest)
    }
}

// Load the JS from resources
func jsScriptText() -> String? {

    guard let jsPath = Bundle.main.path(forResource: "hello", ofType: "js", inDirectory: "WebDocs2/scripts") else {

        return nil
    }
    do
    {
        let jsScript = try String(contentsOfFile: jsPath, encoding: String.Encoding.utf8)
        return jsScript
    }catch{

        print("Error")
        return nil
    }

}
// Run the java script
func runJS(){

    if let jsScript = jsScriptText(){

        let jsContext = JSContext()
        _ = jsContext?.evaluateScript(jsScript)
        let helloJSCore = jsContext?.objectForKeyedSubscript("helloJSCore")
        let result = helloJSCore?.call(withArguments: [])
        print(result?.toString() ?? "Error")

    }
}
于 2017-03-04T13:30:53.460 に答える