1

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>
7
  • how can i reward or accept to those? Commented Dec 1, 2012 at 5:13
  • 1
    @SandeepDhama, Click on the tick mark next to those answers to mark it as correct answer. If you find more useful answers in the same question, you can do an upvote by clicking on the up arrow next to the answer. Commented Dec 1, 2012 at 5:18
  • Check if it is calling the delegate method webView:shouldStartLoadWithRequest:navigationType: on tap of that. If yes, you need to implement it here. Commented Dec 1, 2012 at 5:34
  • No it is not calling the webView:shouldStartLoadWithRequest:navigationType: delegate insid the code. Commented Dec 1, 2012 at 5:39
  • Here's a asynchronous method that I wrote a while back... Check it out: stackoverflow.com/a/12391975/427309 Commented Dec 1, 2012 at 5:51

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

how i can call this registered handler to Objective c can you please help me ?
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.