gpt4 book ai didi

ios - 触发javascript函数时如何在objective c UIWebView中收听

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:02:00 26 4
gpt4 key购买 nike

如何在Objective C中监听javascript方法是否被调用?

例如在 javascript 中:

<script>
function someJsFunction(){}
</script>

如何使用 UIWebView 在 objective c 中实现监听器以监听正在调用的 js 函数。

如何使用以下组件?UIWebView shouldStartLoadWithRequest

如何获取 UIWebView 中的输入框值?

最佳答案

如果你想通过 objective c 在 js 中打印控制台消息,那么你可以使用下面的代码。

//fetch JSContext
//webView is object of UIWebView , in which your js files are already injected
JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//evaluate script on context object
[context evaluateScript:@"var console = {};"]; // make console an empty object
// when ever you use "console.log('')" in your JS it will call below block
context[@"console"][@"log"] = ^(NSString *message)
{
NSLog(@"Console msg from js:%@", message);
};

要从 objective-c 执行 js 函数,请使用以下代码。

NSString *evalScript = [NSString stringWithFormat:@"someJSFun(%@)",param];
[context evaluateScript:evalScript];

现在如果你想从你的 JS 调用 objective c 函数,你可以像下面这样使用 block 。

//Suppose you want to call "someObjCFun(param)" from your js then 
context[@"someObjCFun"]= ^(JSValue *message)
{
//TODO
//This block will be executed when you will call 'someObjCFun(param)' from your js
};

因此,如果您想要 objective-c 中的文本框值,只需像上面那样使用 block 并将文本框值作为参数传递。

附言你的 JS 应该被注入(inject)到 UIWebView 中。

关于ios - 触发javascript函数时如何在objective c UIWebView中收听,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28827317/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com