cocoa webview中调用网页的Javascript函数
首先,我是 Objective-C 和 Cocoa 的新手。我找到了与此相关的资源,但没有一个显示我想要的内容,而且我似乎无法让其他人为我工作。我需要的是一个非常简单的示例,其中包含一个包含按钮的窗口和一个 webview,该 webview 具有一个带有 javascript 函数的 HTML 页面,该函数接受一个参数(字符串或其他内容),并通过 document.write 吐出它
。 (我懂javascript)。
然后,当您单击 webview 外部的按钮时,它将调用 javascript 函数,并且 webview 会通过 document.write
调用说出一些内容。如果有人可以整理一个像这样的快速示例,我将非常感激!
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用 stringByEvaluatingJavaScriptFromString: 在 Web 视图中调用 javascript。
这不是您所要求的完整示例,但完整的应用程序示例在某种程度上超出了 StackOverflow 的适用范围。
You can use stringByEvaluatingJavaScriptFromString: to call javascript in your web view.
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.
如果您只想调用 Javascript 函数,可以这样做:
在 HTML 页面中,您需要以下内容:
If you just want to call a Javascript function, this is the way to do it:
In your HTML page you'll need the following:
以前的解决方案都不适合我。但是,我在Apple Developer中发现了 此方法文档 确实允许我在 webView 中成功执行 JS 代码。
这是一个在 XCode 4.6.1 (OS X 10.8.3) 中为我工作的示例:
[[webView windowScriptObject]valuWebScript:@"document.write('derp')"];
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')"];
要使 WebView 正常工作,请参阅 Lost Decade Games 提供的这个很棒的教程:
如何将 HTML5 嵌入本机 Mac OSX 应用程序。
To get the WebView working see this awesome tutorial by Lost Decade Games:
How to embed HTML5 into a native Mac OSX app.
您应该尝试查看我对此问题的回答 - 在 iPhone 应用程序中显示 HTML
然后您通过将 javascript 添加到您的 XCode 项目文件中,可以将 javascript 用作普通的 html 标准。
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.