我们有一个网页,其中包含6个用autocomplete="one-time-code"
标签的输入字段。我们正在使用keyup
事件来自动聚焦到下一个输入字段。可以在Safari中正常工作,当用户单击OTP建议框时,每个输入字段都会从OTP中获得一位数字。但是在WKWebView
中,它会在第一个输入框中设置OTP的所有数字。通过在所有事件侦听器中添加日志,似乎在WKWebView
中,当用户尝试使用建议框填充OTP时,页面未触发keyup
或focus
或任何其他事件。以下是摘自here的相关代码:
function getCodeBoxElement(index) {
return document.getElementById('codeBox' + index);
}
function onKeyUpEvent(index, event) {
const eventCode = event.which || event.keyCode;
if (getCodeBoxElement(index).value.length === 1) {
if (index !== 6) {
getCodeBoxElement(index+ 1).focus();
} else {
getCodeBoxElement(index).blur();
// Submit code
console.log('submit code ');
}
}
if (eventCode === 8 && index !== 1) {
getCodeBoxElement(index - 1).focus();
}
}
function onFocusEvent(index) {
for (item = 1; item < index; item++) {
const currentElement = getCodeBoxElement(item);
if (!currentElement.value) {
currentElement.focus();
break;
}
}
}
<body>
<input id="codeBox1" autocomplete="one-time-code" type="number" maxlength="1" onkeyup="onKeyUpEvent(1, event)" onfocus="onFocusEvent(1)"/>
<input id="codeBox2" autocomplete="one-time-code" type="number" maxlength="1" onkeyup="onKeyUpEvent(2, event)" onfocus="onFocusEvent(2)"/>
<input id="codeBox3" autocomplete="one-time-code" type="number" maxlength="1" onkeyup="onKeyUpEvent(3, event)" onfocus="onFocusEvent(3)"/>
<input id="codeBox4" autocomplete="one-time-code" type="number" maxlength="1" onkeyup="onKeyUpEvent(4, event)" onfocus="onFocusEvent(4)"/>
<input id="codeBox5" autocomplete="one-time-code" type="number" maxlength="1" onkeyup="onKeyUpEvent(5, event)" onfocus="onFocusEvent(5)"/>
<input id="codeBox6" autocomplete="one-time-code" type="number" maxlength="1" onkeyup="onKeyUpEvent(6, event)" onfocus="onFocusEvent(6)"/>
</body>
我还尝试在WKWebView
中注入脚本来侦听某些事件,但是在使用自动OTP的情况下运气不好。
let contentController = WKUserContentController()
let scriptSource = """
document.getElementsByName("codeBox1")[0].addEventListener("keyup", function(){ window.webkit.messageHandlers.iosListener.postMessage('key up 1'); });
document.getElementsByName("codeBox1")[0].addEventListener("change", function(){ window.webkit.messageHandlers.iosListener.postMessage(this.value); });
"""
let script = WKUserScript(source: scriptSource, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
contentController.addUserScript(script)
wkWebView.configuration.userContentController.addUserScript(script)
wkWebView.configuration.userContentController.add(self, name: "iosListener")
public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
print("message: \(message.body)")
}
有什么办法可以像WKWebView
那样处理Safari
?还没有在SFSafariViewController
上尝试过,这对我们来说不是一个选择。