8

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.

5 Answers 5

16

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.

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

2 Comments

My problem is where do I specify webView? I can add a webview in interface builder, but how do I connect it with that code?
The most common way is to use IBOutlets (developer.apple.com/library/ios/#DOCUMENTATION/Cocoa/Conceptual/…). If this is new to you I think you would benefit from working through one of the many Cocoa tutorial books like Cocoa Programming for Mac OSX amazon.com/Cocoa-Programming-Mac-OS-3rd/dp/0321503619
7

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>

Comments

4

None of the previous solutions worked for me. However, I found this method in the Apple Developer documentation which did allow me to execute JS code in my webView successfully.

Here is an example that worked for me in XCode 4.6.1 (OS X 10.8.3):

[[webView windowScriptObject] evaluateWebScript:@"document.write('derp')"];

Comments

2

To get the WebView working see this awesome tutorial by Lost Decade Games:

How to embed HTML5 into a native Mac OSX app.

Comments

0

You should try to see my answer on this question - Displaying HTML in iPhone app

then you can use javascript as just normal html standard by add them to your XCode project's file.

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.