読者です 読者をやめる 読者になる 読者になる

あぷせめも

アプリ開発とか電子工作とか。

【Swift】UIWebViewの中のJS関数を呼び出す方法

案外簡単でした。

UIWebView#stringByEvaluatingJavaScriptFromString

安定のメソッド名の長さ

このメソッドにJSを書きます。
関数を呼び出す一文を文字列で渡します。

webview.stringByEvaluatingJavaScriptFromString("hogeFunction();")

fuga.html(今回はローカルに配置)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<script>
        function hogeFunction(fuga){
            document.getElementById('content').innerText = fuga;
            alert(fuga);
        }
	</script>
</head>
<body>
    <div id="content" style="font-size:xx-large;">
       testtesttesttesttest
    </div>
</body>
</html>

ViewController.swift

import UIKit

class ViewController: UIViewController, UIWebViewDelegate{

    @IBOutlet var webview: UIWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //テストとして上記のfuga.htmlをひらく
        var req = NSURLRequest(URL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("fuga", ofType: "html")!)!)
        webview.loadRequest(req)
    }

    //実行部分    
    @IBAction func executeHogeFunction(sender: UIButton) {
        webview.stringByEvaluatingJavaScriptFromString("hogeFunction('\(UIDevice().systemVersion)');")
    }
}

実行

f:id:ApstndbOnsen:20150612143102p:plain
ボタン押下
f:id:ApstndbOnsen:20150612143059p:plain

 

サニタイジングを忘れないこと

ユーザーが任意の文字を入れてそれをページに表示させるような場合は、
XSS対策として適切にサニタイジングをしてから
「innerHTML = hoge;」をしましょう。

勝手に中身をエスケープをしてくれる
innerTextかtextContentを使いましょう。

innerTextはFirefox
textContentはIEで使えないのがなんかあれですけど...