简体   繁体   中英

communication from javascript to objective-C

I am loading a HTML file file from server inside UIWebView. In HTML file, we have external links to open and a Javascript function is written to handle that events.I want to open that hyperlinks inside a seperate new webview within the app.

Is there any way that server side javascript method notify to objective-C or any callback function which will call in objective-C and then i can do someting in my code? i have seen the example of WEBViewJavaScriptBridge to communicate between javascript and objective C. but they are using the local HTML file to load and communicate.Bt my HTML file is on server side.It would be great if anyone can help on this.

I am puuting a sample HTML file here. We have two hypelinks "Open" and "Close" on taping on open button a function is called that show alert. so instead of alert i want to pass the retuen callback to objective-C code.

Here it is:-

<!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>

You can communicate with your HTML from objective c with the following webView delagate methods...

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

Please go through the usage of these methods... I hope this may help you

I used webviewjavascriptbridge to communicate javascript and objective C code.

In this example code, note the global variable of 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>

Reference: https://github.com/marcuswestin/WebViewJavascriptBridge

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM