WKWebView即使启用Java脚本也无法正常工作-Swift

时间:2018-12-26 05:53:32

标签: javascript ios swift wkwebview

我正在尝试使用WKWebView显示一个webView及其内容。我使用了以下代码,并且webView显示了其内容。问题是,有一个功能可以在单击webView内的按钮/文本字段时显示自动填充下拉列表。并且在启用javascript后在android上运行良好,但是即使我按照以下代码启用了javascript,它也对我不起作用。 (参考:https://stackoverflow.com/a/47038285/5416775

private var webView: WKWebView!

   let preferences = WKPreferences()
   preferences.javaScriptEnabled = true
   let configuration = WKWebViewConfiguration()
   configuration.preferences = preferences
   webView = WKWebView(frame: view.bounds, configuration: configuration)

以及php团队使用以下代码动态显示下拉菜单的功能。

$('input[name=\'option\']').autocomplete({
 'source': function(request, response) {
   $.ajax({
 url: 'index.php?route=product/product_option/autocomplete&language_id=<?php echo $language_id; ?>&store_id=<?php echo $store_id; ?>&filter_name=' +  encodeURIComponent(request),
 dataType: 'json',     
 success: function(json) {
   response($.map(json, function(item) {
     return {
       category: item['category'],
       label: item['name'],
       value: item['option_id'],
       type: item['type'],
       option_value: item['option_value']
         }
       }));
     }
   });
 },
 'select': function(item) {
   html  = '<div class="tab-pane" id="tab-option' + option_row + '">';
    html += ' <input type="hidden" name="product_option[' + option_row + '][product_option_id]" value="" />';
   html += ' <input type="hidden" name="product_option[' + option_row + '][name]" value="' + item['label'] + '" />';
   html += ' <input type="hidden" name="product_option[' + option_row + '][option_id]" value="' + item['value'] + '" />';
   html += ' <input type="hidden" name="product_option[' + option_row + '][type]" value="' + item['type'] + '" />';

   if (item['type'] == 'checkbox') {
   html += ' <div class="form-group">';
   html += '   <label class="col-sm-12 control-label text-danger"><?php echo $entry_text_required; ?></label>';
   html += ' </div>';
   }

   html += ' <div class="form-group" style="display: none;">';
   html += '   <label class="col-sm-2 control-label" for="input-required' + option_row + '"><?php echo $entry_required; ?></label>';
   html += '   <div class="col-sm-10"><select name="product_option[' + option_row + '][required]" id="input-required' + option_row + '" class="form-control">';
   html += '       <option value="1"><?php echo $text_yes; ?></option>';
   html += '       <option value="0"><?php echo $text_no; ?></option>';
   html += '   </select></div>';
   html += ' </div>';

   html += ' <div class="form-group" style="display: none;">';
   html += '   <label class="col-sm-2 control-label" for="input-option-sort-order' + option_row + '"><?php echo $entry_option_sort_order; ?></label>';
var option_row = <?php echo $option_row; ?>;

任何解决方案..?将不胜感激。谢谢..!

2 个答案:

答案 0 :(得分:1)

我已经测试了您的新网址,并且工作正常。尝试使用以下代码:

import UIKit
import WebKit
class WebViewController: UIViewController {

    let webView: WKWebView = {
        let v = WKWebView()
        return v
    }()

    lazy var backButton: UIButton = {
        let v = UIButton()
        v.layer.cornerRadius = 5
        v.clipsToBounds = true
        v.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        v.setTitle("<", for: .normal)
        v.setTitleColor(.white, for: .normal)
        return v
    }()

    var url: String?
    var activityIndicator: UIActivityIndicatorView?


    func setupUI(){
        view.backgroundColor = .black
        activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
        activityIndicator?.center = self.view.center
        [webView,backButton,activityIndicator!].forEach{view.addSubview($0)}
        webView.fillSuperView()
        if #available(iOS 11.0, *) {
            backButton.anchor(top: view.safeAreaLayoutGuide.topAnchor, left: view.leadingAnchor, bottom: nil, right: nil, size: .init(width: 30, height: 30), padding: .init(top: 8, left: 20, bottom: 0, right: 0))
        } else {
             backButton.anchor(top: topLayoutGuide.bottomAnchor, left: view.leadingAnchor, bottom: nil, right: nil, size: .init(width: 30, height: 30), padding: .init(top: 8, left: 20, bottom: 0, right: 0))
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        backButton.addTarget(self, action: #selector(didSelect(_:)), for: .touchUpInside)

    }

    @objc func didSelect(_ sender: UIView){
        switch sender {
        case backButton:
            navigationController?.popViewController(animated: true)
        default:
            break
        }
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        webView.navigationDelegate = self
        webView.load(URLRequest(url: URL(string: url ?? "https://demo.dukanje.com/index.php?route=product/product_option&product_id=206&store_id=52&language_id=1")!))
        activityIndicator?.startAnimating()
    }
}

extension WebViewController: WKNavigationDelegate{
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        self.activityIndicator?.stopAnimating()
        self.activityIndicator?.removeFromSuperview()
        self.activityIndicator = nil
    }
}

我使用扩展程序来帮助布局:

extension UIView{

    func fillSuperView(){
        translatesAutoresizingMaskIntoConstraints = false
        guard let superview = superview else {return}
        anchor(top: superview.topAnchor, left: superview.leadingAnchor, bottom: superview.bottomAnchor, right: superview.trailingAnchor)
    }



    func anchor(top: NSLayoutYAxisAnchor?, left: NSLayoutXAxisAnchor?, bottom: NSLayoutYAxisAnchor?, right: NSLayoutXAxisAnchor?, size: CGSize = .zero, padding: UIEdgeInsets = .zero){
        translatesAutoresizingMaskIntoConstraints = false
        if let top = top{
            topAnchor.constraint(equalTo: top, constant: padding.top != 0 ? padding.top : 0).isActive = true
        }
        if let left = left{
            leadingAnchor.constraint(equalTo: left, constant: padding.left != 0 ? padding.left : 0).isActive = true
        }
        if let bottom = bottom{
            bottomAnchor.constraint(equalTo: bottom, constant: padding.bottom != 0 ? -padding.bottom : 0).isActive = true
        }
        if let right = right{
            trailingAnchor.constraint(equalTo: right, constant: padding.right != 0 ? -padding.right : 0).isActive = true
        }
        if size.width != 0{
            widthAnchor.constraint(equalToConstant: size.width).isActive = true
        }
        if size.height != 0{
            heightAnchor.constraint(equalToConstant: size.height).isActive = true
        }
    }
}

第一enter image description here 第二enter image description here

答案 1 :(得分:0)

1)允许NSAppTransportSecurity进入Plist文件。

<key>NSAppTransportSecurity</key><dict><key>NSAllowsArbitraryLoads</key>
  <true/>
</dict>

2)导入WebKit

3)创建@IBOutlet弱变量webView:WKWebView!

4)在ViewDidLoad中编写此代码

  let imgUrl = "http://demo.dukanje.com/index.php?route=product/product_option&product_id=206&store_id=cWJaWkdNcTBSVHRtYkkyaDRjK0laQT09..52&language_id=1"
    DispatchQueue.main.async {
        self.webView.loadHTMLString("<html><body><p><select>\(imgUrl)</select></p></body></html>", baseURL: nil)

    }