iOS開發--OC調用JS篇


OC調用JS篇

其中相對應的html部分如下:

<html>
    <header>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script type="text/javascript">

            function secondClick() {
                share('分享的標題','分享的內容','圖片地址');
            }

        function showAlert(message){
            alert(message);
        }

        </script>
    </header>

    <body>
        <h2> 這里是第二種方式 </h2>
        <br/>
        <br/>
        <button type="button" onclick="secondClick()">Click Me!</button>

    </body>
</html>

方式一

NSString *jsStr = [NSString stringWithFormat:@"showAlert('%@')",@"這里是JS中alert彈出的message"];
[_webView stringByEvaluatingJavaScriptFromString:jsStr];

注意:該方法會同步返回一個字符串,因此是一個同步方法,可能會阻塞UI。

方式二 (推薦這種)

使用JavaScriptCore庫來做JS交互。

JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
NSString *textJS = @"showAlert('這里是JS中alert彈出的message')";
[context evaluateScript:textJS];

原文鏈接:http://www.jianshu.com/p/d19689e0ed83


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM