1. 程式人生 > >JavaScript直接呼叫OC程式碼

JavaScript直接呼叫OC程式碼

在專案中需要通過UIWebVIew開啟一個網頁,在網頁中點選按鈕彈出oc的對話方塊。

在UIWebview中載入的js程式碼中通過改變document.locations=“”


// 需要使用javascriptCore.framework庫


#import <JavaScriptCore/JavaScriptCore.h>



// index.html 程式碼
<!DOCTYPE html>

<html lang="en">
    
    <head>
        
         <meta charset="utf-8">
            
          <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    
                
            <meta name="description" content="">
                    
            <meta name="viewport" content="width=device-width; initial-scale=1.0">
             <script type="text/javascript" src="index.js"></script>           
      
                        
      </head>
    
	<button id="hallo" onclick="buttonClick()"> 點選button</button>

    </body>
    
</html>

該函式在index.js中定義
function buttonClick()
{
	close_page("hello world");
}





意思是點選這個button,就呼叫close_page()函式,close_page()函式顯然是我們在oc中實現的一個block段,



JSContext *context = [self.webview valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];

獲取該UIWebview的javascript執行環境。



// 在webView 函式中 寫入 回撥的函式名稱 為close_page
#pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    
    // 點選完成按鈕 返回上頁面  js 與 oc 互動
    JSContext *context = [webView  valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    context[@"close_page"] = ^() {
        NSArray *args = [JSContext currentArguments];
        for (JSValue *titleName in args) {
            NSLog(@"title--%@", titleName);
        }
    };
}