gpt4 book ai didi

android - Swift:WKWebView 添加像 Android 一样的 javascript 界面

转载 作者:行者123 更新时间:2023-11-30 10:39:21 25 4
gpt4 key购买 nike

我有一个页面想要在具有动态内容的 WebView 中显示。

在Android上我可以通过界面简单地做到这一点,这是界面:

class WebAppInterface (val context: Context, val userId: Long, val  type: String) {
@JavascriptInterface
fun getId(): Long {
return userId
}

@JavascriptInterface
fun getBaseUrl(): String{
return Configuration.getInstance().userConfig.getStoredBaseUrl();
}

@JavascriptInterface
fun getGetStatType(): String{
return type;
}
}

webview.addJavascriptInterface(WebAppInterface(this.applicationContext, id, statsType!!), "android")

我如何在 iOS 上做同样的事情,在我搜索后我得到了这个:

let contentController = WKUserContentController()
contentController.add(self, name: "android") // -> Set a listener

let config = WKWebViewConfiguration()
config.userContentController = contentController

let scriptString = "????? What write ir?"
let script = WKUserScript(source: scriptString, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true)
config.userContentController.addUserScript(script)

webView = WKWebView(frame: .zero, configuration: config)

以及委托(delegate)方法:

 func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
print(message)
}

在委托(delegate)方法中,当到达关键字 android? 时,它不会打印?为什么?是不是我对操作的理解有误?这是我的一些 js 代码,它与 androidInterface 配合良好

function getSteps() {
const url = android.getBaseUrl() + 'patient/' + android.getId() + '/statistics/steps?from=' + from + '&to=' + to;
Http.open("GET", url);
Http.setRequestHeader('Authorization', 'Bearer ' + android.getToken())
Http.send();
}

如何将值注入(inject)“android”js,就像我在 android 上所做的那样。

最佳答案

我通过注入(inject)手动创建的 android 对象解决了这个问题,如下所示:

let scriptString = """
var android = {
getGetStatType: function() {
return 'sleep';
},
getId: function() {
return 98;
},
getBaseUrl: function() {
return 'baseUrl';
},
getToken: function() {
return 'myToken';
}
};
"""
let script = WKUserScript(source: scriptString, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: true)
config.userContentController.addUserScript(script)

关于android - Swift:WKWebView 添加像 Android 一样的 javascript 界面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57203996/

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