Search code examples
swiftimagemacosgoogle-chromewebkit

How can i show images in webkit?


Current status

  • I have developed a simple Mac OS application.
  • This application searches recipes by WebKit.

    import Cocoa
    import WebKit
    
    class ViewController: NSViewController {
    
    @IBOutlet weak var searchTextField: NSTextField!
    @IBOutlet weak var browserWebView: WKWebView!
    override func viewDidLoad() {
        super.viewDidLoad()
        browserWebView.translatesAutoresizingMaskIntoConstraints = true
        searchTextField.translatesAutoresizingMaskIntoConstraints = true
        let StringURL:String = "https://www.google.co.jp/search?q=ピザ+inurl:/recipe/+site:cookpad.com"
        let url = URL(string:StringURL.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!)
        let urlRequest = URLRequest(url: url!)
        self.browserWebView.load(urlRequest)
    
    }
    override var representedObject: Any? {
        didSet {
        }
    }
    }
    

Problem

  • GoogleChrome shows food images, but WebKit doesn’t (see images below).

    • GoogleChrome

    GoogleChrome

    • WebKit(Xcode Simulatror)

    WebKit(Xcode Simulatror)

  • I want to read enough texts also images, so I choose not "image tab" but "all tab" option

Question

  • How can i show images by webkit?

Development Environment

  • Swift3

Tried → Error

  • Tried : Google Chrome view with JavaScript disabled is the same result as WebKit (Xcode Simulator). So I added the following code.

    let preferences = WKPreferences()
    preferences.javaScriptEnabled = true
    
    let configuration = WKWebViewConfiguration()
    configuration.preferences = preferences
    

    →Error : Default WebKit enables JavaScript, so this approach doesn’t resolve the problem.

Best regards,


Solution

  • I added customUserAgent in viewDidLoad() to solve this problem.

    browserWebView.customUserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36”
    
    • WebKit(Xcode Simulatror)

    CookingLog_customUserAgent