我在 WebView 中有一个按钮。
单击按钮时,我想将该项目添加到我的 native 代码数组中。
然后,当再次按下它时,我想删除数组中的项目。
我的问题是:逻辑中缺少什么?按下按钮时,不会调用 userContentController
或 decidePolicyForNavigationAction
。
JavaScript 代码
<script type = "text/javascript">
function someFunction(id) {
if(id = true) {
document.getELementById("someid").innerText = " some title state 1"
} else {
document.getELementById(someid).innerText = " some title state 2"
}
}
<script>
Html 按钮
<button class=someclass id="someid" onclick= "Some.listCallBack()">Add List</button>
Objective C 代码
TableViewCell.h
@interface TableViewCell : UITableViewCell <WKNavigationDelegate, WKScriptMessageHandler>
@property (nonatomic,strong) IBOutlet WKWebView *webView;
TableViewCell.m
- (void)awakeFromNib {
[[[self.webView configuration] userContentController]addScriptMessageHandler:selfname:@"someid"];
}
- (void)userContentController:(nonnull WKUserContentController *)userContentController
didReceiveScriptMessage:(nonnull WKScriptMessage *)message {
// i will handle event here
}
最佳答案
由于问题中似乎省略了实际的点击处理程序,因此很难判断确切的问题是什么。因此,我可能会陈述显而易见的事情,但我们开始吧。
处理程序(使用 -addScriptMessageHandler:name:
注册的处理程序)作为 webkit.messageHandlers
上的属性向 JavaScript 公开。从这里开始,进程间通信看起来或多或少类似于向另一个窗口发送消息,只不过我们使用的是 webkit.messageHandlers.handlerID.postMessage()
而不是 window.postMessage()
。换句话说,
function clickHandler() {
webkit.messageHandlers.someid.postMessage("The message we’d like to pass to our WKScriptMessageHandler");
}
应该做。
关于javascript - 在 Objective-C 中处理 Javascript onclick 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60894232/