簡體   English   中英

從 javascript 到 Objective-C 的通信

[英]communication from javascript to objective-C

我正在從 UIWebView 內的服務器加載一個 HTML 文件文件。 在 HTML 文件中,我們有外部鏈接要打開,並編寫了一個 Javascript 函數來處理該事件。我想在應用程序內的一個單獨的新 web 視圖中打開該超鏈接。

服務器端javascript方法有什么方法可以通知objective-C或任何將在objective-C中調用的回調函數,然后我可以在我的代碼中做一些事情嗎? 我已經看到了 WEBViewJavaScriptBridge 在 javascript 和目標 C 之間進行通信的示例,但他們使用本地 HTML 文件來加載和通信。Bt 我的 HTML 文件在服務器端。如果有人能對此提供幫助,那就太好了。

我在這里 puuting 一個示例 HTML 文件。 我們在點擊打開按鈕時有兩個超鏈接“打開”和“關閉”,一個函數被稱為顯示警報。 所以我想將 retuen 回調傳遞給 Objective-C 代碼而不是警報。

這里是:-

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width = device-width, initial-scale = 1.0, maximum-scale = 1.0, minimum-scale = 1.0, user-scalable=no"/>
<meta name="HandheldFriendly" content="True"/>
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<title>Test HTML</title>
<script type="text/javascript">

function open(url, offset){
alert("Open Webview with url:"+ url + " & Offset: " + offset);
}

function close(url, offset){
alert("close webview");
}

</script>
</head>
<body>
<a href="javascript:open('http://www.tcm.com', '55')">Open</a><br>
<a href="javascript:close()">Close</a>
</body>
</html>

您可以使用以下 webView delagate 方法與目標 c 中的 HTML 進行通信...

- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

請仔細閱讀這些方法的使用...希望對您有所幫助

我使用 webviewjavascriptbridge 來交流 javascript 和目標 C 代碼。

在此示例代碼中,請注意 bridge 的全局變量。

<!doctype html>
<html><head>
<style type='text/css'>
    html { font-family:Helvetica; color:#222; }
    h1 { color:steelblue; font-size:24px; margin-top:24px; }
    button { margin:0 3px 10px; font-size:12px; }
    .logLine { border-bottom:1px solid #ccc; padding:4px 2px; font-family:courier; font-size:11px; }
</style>
</head><body>
<h1>WebViewJavascriptBridge Demo</h1>
<script>
window.onerror = function(err) {
    alert('window.onerror: ' + err)
}
var bridge;
document.addEventListener('WebViewJavascriptBridgeReady', onBridgeReady, false)
function onBridgeReady(event){
    alert("Onbridge ready call");

    bridge = event.bridge
    var uniqueId = 1
    function log(message, data) {
        var log = document.getElementById('log')
        var el = document.createElement('div')
        el.className = 'logLine'
        el.innerHTML = uniqueId++ + '. ' + message + (data ? ': ' + JSON.stringify(data) : '')
        if (log.children.length) { log.insertBefore(el, log.children[0]) }
        else { log.appendChild(el) }
    }
    bridge.init(function(message) {
        log('JS got a message', message)
    })

    bridge.registerHandler('open', function(data, response) {
                           log('JS handler testJavascriptHandler was called', data)
                           response.respondWith({ 'Javascript Says':'open open open!' })
                           })



    bridge.registerHandler('testJavascriptHandler', function(data, response) {
        log('JS handler testJavascriptHandler was called', data)
        response.respondWith({ 'Javascript Says':'Right back atcha!' })
    })

    var button = document.getElementById('buttons').appendChild(document.createElement('button'))
    button.innerHTML = 'Send message to ObjC'
    button.ontouchstart = function(e) {
        e.preventDefault()
        bridge.send('Hello from JS button')
    }

    document.body.appendChild(document.createElement('br'))

    var callbackButton = document.getElementById('buttons').appendChild(document.createElement('button'))
    callbackButton.innerHTML = 'Fire testObjcCallback'
    callbackButton.ontouchstart = function(e) {
        e.preventDefault()
        log("Calling handler testObjcCallback")
        bridge.callHandler('testObjcCallback', {'foo': 'bar'}, function(response) {
            log('Got response from testObjcCallback', response)
        })
    }

}



function open(url, offset,e)
{
    alert(bridge);

    //alert("Open Webview with url:Yes Got it");



   //  alert(document.getElementById(offset).href);
    //  var bridge = event.bridge;
   // alert(bridge);

    window.location = url+'?offset='+offset//'myapp:myaction:url:offset'

    //requestFromObjc("buttonColor&someParam=1");
}


function close()
{
        alert("Open Webview with url:"+ url + " & Offset: " + offset);
}

function requestFromObjc(functionName, objcResult, callback)
{
    if (!objcResult)
    {
        window.location = 'myapp:myaction:param1:param2'
       // window.location = "myapp://objcRequest?function=" + functionName + "&callback=" + arguments.callee.name + "&callbackFunc=" + arguments.callee.caller.name;
    }
    else
    {
        window[callback](objcResult);
    }
}

</script>
<div id='buttons'></div> <div id='log'></div>

<body>
    <a id="55" href="javascript:open('http://www.tcm.com', '55',this)">Open</a><br>
    <a href="javascript:close()">Close</a>
</body>

</body></html>

參考: https : //github.com/marcuswestin/WebViewJavascriptBridge

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM