我的应用程序中有一个 WkWebView,它将用户带到第三方网页,他们必须登录才能访问相关信息。该应用程序的所有用户都使用相同的预共享登录详细信息(应用程序由企业分发给少数人管理)。
我希望应用程序自动填写用户名和密码详细信息,然后在无需用户输入的情况下提交所有内容。我一直在这里查看很多帖子,并尝试使用 webViewDidFinishLoad 发出帖子请求,但到目前为止还没有运气。大多数信息都是关于存储和调用用户详细信息,而不是预先共享的用户名和密码。
任何帮助指出正确方向的帮助都会很棒。
当前用于加载网站的代码是:
导入UIKit 导入WebKit
class TreliskeWeatherViewController: UIViewController, WKUIDelegate {
var webView: WKWebView!
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
webView.navigationDelegate = self
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
let treliskeWeather = URL(string: " ")
let myRequest = URLRequest(url: treliskeWeather!)
webView.load(myRequest)
}
}
extension TreliskeWeatherViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("Finished navigating to url")
}
}
最佳答案
Web View 加载完成后,您可以评估 JavaScript 文件。我在 javascript 中使用超时和间隔逻辑只是为了确保元素存在。我在这里只检查登录按钮,但如果您愿意,您可以检查所有三个按钮。
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
guard let jsFile = Bundle.main.url(forResource: "injectCredentials", withExtension: "js") else {
return
}
do {
let injectJS = try String(contentsOf: jsFile)
let formatted = String(format: injectJS, "username", "password")
webView.evaluateJavaScript(formatted) { (value, error) in
//
}
} catch {
//
}
}
注入(inject)Credentials.js
var timeoutSeconds = 30;
var username = "%@";
var password = "%@";
var checkLogin = setInterval(checkLoginFields, 1000);
setTimeout(function() {
clearInterval(checkLogin);
}, timeoutSeconds * 1000);
function checkLoginFields() {
var usernameInput = document.getElementById('username');
var passwordInput = document.getElementById('password');
var signInButton = document.getElementById("login");
if (signInButton == null) {
return;
}
usernameInput.value = username;
passwordInput.value = password;
signInButton.click();
clearInterval(checkLogin);
}
关于swift - 使用swift 4自动登录网页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50917303/