Swift...在运行时更改 .js 文件的变量 [英] Swift...Change variable of .js file during runtime
问题描述
我正在开发具有 WKwebview 的 IO 应用程序,我将配置设置为注入 .js 文件.
am working on an IOs application that has a WKwebview and i set the configuration to inject a .js file.
这是我的 javascript 文件.
this is my javascript file.
var User = ""
var Pass = ""
document.getElementsByName('username')[0].value = User
document.getElementsByName('password')[0].value = password
submitButton()
现在当我事先给变量值时代码运行完美.但是我稍后会尝试从 NSUserDefualts 更改 User 和 Pass 的值,但我不知道从哪里开始.
now the code runs perfect when i give the variables value before hand. however i am trying to change the value of User and Pass from NSUserDefualts later on but i have no idea where to start.
我尝试在没有帮助的情况下使用 javascript 框架.
i tried playing around with javascript framework with no help.
任何想法或方向将不胜感激.
any idea's or direction would be highly appreciated.
谢谢
推荐答案
我设法解决了这个问题,而不是沿着注入 javascriptfile 路径,而是通过保存用户并在 NSUserDefaults 中传递变量并从方法运行 javascript在我的 UIViewController 中
i managed to work around the problem not going down the injecting javascriptfile path, i but by saving the user and pass variables in NSUserDefaults and running the javascript from a method inside my UIViewController
代码并不漂亮,但它可以工作并且看起来像这样:
the code is not pretty but it works and looks something like this:
// the passed would be stored in NSUserDefaults
let passwd = "test"
// passEdited simply adds ' ' to the passwd you can just add them to the passwd variable but i like to see every step i am taking
let passEdited = "'" + passwd +"'"
// this is the actual java code i would like to run
var passJS = "document.getElementByName('password')[0].value =" + passEdited
// check for correct Url before running the java code
if webView.URL?.absoluteString == "www.YOURWEBSITE" {
webView.evaluteJavaScript(passJS, completionHandler: nil)
这篇关于Swift...在运行时更改 .js 文件的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!