Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Javascript function of webpage in cocoa webview

First, I'm a complete newbie at objective-c and cocoa. I've found resources related to this, but none showing what I want, and I can't seem to get the others to work for me. What I need is a really dumbed-down example with a window containing a button and a webview that has an HTML page with a javascript function that takes one parameter (a string or something), and spits it out via document.write. (I know javascript).

Then when you click the button outside of the webview, it will call the javascript function, and the webview will say something, from the document.write call. If someone could perhaps put together a quick example like this, I'd really appreciate it!

Thanks.

like image 794
penguinrob Avatar asked Apr 25 '11 23:04

penguinrob


2 Answers

You can use stringByEvaluatingJavaScriptFromString: to call javascript in your web view.

[ webView stringByEvaluatingJavaScriptFromString: @"myJavascriptFunction()" ];

This is not as complete an example as you have asked for but a complete application example is somewhat beyond what is appropriate for StackOverflow.

like image 123
Jon Steinmetz Avatar answered Sep 18 '22 13:09

Jon Steinmetz


If you just want to call a Javascript function, this is the way to do it:

WebScriptObject *script = [_webView windowScriptObject];
[script callWebScriptMethod:@"jsFunctionWithText" withArguments:@[@"Some text"]];

In your HTML page you'll need the following:

<script>
function jsFunctionWithText(text)
{
    document.write(text);
}
</script>
like image 36
Mark Ingram Avatar answered Sep 18 '22 13:09

Mark Ingram