Loading local HTML with local Javascript Sources in a WKWebView (iOS, Swift)

load local html file in webview ios swift
wkwebview load local image
wkwebview load local file
load html string in webview ios swift 4
wkwebview inject javascript
load html file in wkwebview ios swift 4
swift javascript
javascript in ios

I am trying to load a local html file in a WKWebView for a iOS app (Swift 4.2). Unfortunately, this local file contains javascript code that does not seem to be executed.

Below is this html file (taken from https://www.verovio.org/tutorial.xhtml?id=topic00):

<html>
    <head>
        <title>Verovio Hello World! example</title>
        <script src="verovio-toolkit.js" type="text/javascript" ></script>
        <script src="jquery-3.1.1.min.js" type="text/javascript" ></script>
    </head>
    <body>
        Hello World!
        <div id="svg_output"/>
        <script type="text/javascript">
            var vrvToolkit = new verovio.toolkit();
            $.ajax({
               url: "Beethoven_StringQuartet_op.18_no.2.mei"
               , dataType: "text"
               , success: function(data) {
               var svg = vrvToolkit.renderData(data);
               $("#svg_output").html(svg);
               }
               });
        </script>
    </body>
</html>

And below the view controller file written in swift:

import UIKit
import WebKit

class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {

    @IBOutlet weak var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        webView.uiDelegate = self
        webView.navigationDelegate = self

        let url = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "html")!
        webView.loadFileURL(url, allowingReadAccessTo: url)
    }
}

Files are local under "Build Phases/Copy Bundle Resources" in the project properties. I also tried to put them in a directory but without any success. Below the file organization inside the project.

EDIT: When I change the url in the html file from Beethoven.mei to https://www.verovio.org/gh-tutorial/mei/Beethoven_StringQuartet_op.18_no.2.mei (same file but on Verovio's website), anything works good!!

So:

  • Local .js resources work fine

  • The issue comes from jquery not able to load local text file

Any idea on how to make jquery able to load the local file?

Thank you!

M.

First check your index.html file has scr path for js. if like below, that means js files contain in js folder. so you need to add reference to that folder while add to project.

<script src="js/jquery.js"></script>

then get the main resource path like below

let path = Bundle.main.resourcePath! + "/\(folderName)/\(fileName)"
print("path:=",path )

after that load that file to webView

do {
    let contents =  try String(contentsOfFile: path, encoding: .utf8)
    let baseUrl = URL(fileURLWithPath: path)
    webView.loadHTMLString(contents as String, baseURL: baseUrl)
} catch {
    print ("File HTML error")
}

garynewby/WKWebViewLocal: WKWebView loading local , Code Issues 0 Pull requests 0 Projects 0 Actions Security 0 Pulse. WKWebView loading local files and calling between Javascript and Swift. ios wkwebview  wkwebview-local-resources. iOS project with a WKWebView that loads local resources, based on one of my SO answers. Currently supported: Local HTML, CSS and JS files; Remote HTML, CSS and JS files (as requested by edon2005): downloading a zip & unzipping (Alamofire + Zip)

According to the docs, loadFileURL does this:

If readAccessURL references a single file, only that file may be loaded by WebKit. If readAccessURL references a directory, files inside that file may be loaded by WebKit.

The url you got is a url of a file, namely the HTML file. You need the url of the directory. You can do this by calling deletingLastPathComponent:

webView.loadFileURL(url, allowingReadAccessTo: url.deletingLastPathComponent())

Inject JavaScript into WKWebView, In Swift, it is possible to inject a JavaScript code into a WKWebView and execute Load HTML file from a local file,; Load JavaScript code from a local file,; Create let js = getMyJavaScript(); let script = WKUserScript(source: js, injectionTime: . Complete Swift 3 training - Get ready for XCode 8 and ios 10  Loading local content WKWebView can load any HTML stored in your app bundle using its loadFileURL() method. You should provide this with a URL to some HTML file that you know is in your bundle, along with another URL that stores any other files you want to allow the web view to read.

You can use the loadHTMLString method to load the HTML, as below:

let url = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "html")!
do {
    let html = try String(contentsOf: url)
    webView.loadHTMLString(html, baseURL: url.deletingLastPathComponent())
} catch ....

The baseURL point to your app directory in file system. You can write in the src property of the script tag relative location that is interpreted as relative to baseURL.

How To Load HTML File In WebView In Swift 4 Xcode 9 ( Hindi , Add the local HTML file into your project name it as index.html, then create request to Duration: 5:53 Posted: Dec 27, 2017 I am trying to load a local html file in a WKWebView for a iOS app (Swift 4.2). Unfortunately, this local file contains javascript code that does not seem to be executed. Below is this html file

load local file in webview ios using http proto |Apple Developer , Is there any way to create the server in iOS to run a web-view? I want to run a local HTML file in a web-view with a local-host URL. Use WKWebView and load your HTML as a string. -B5B1-574A0E2B0728/Documents/xxxxx.js">), it will fail to load. source 'https://github.com/CocoaPods/Specs.git'. Add the local HTML file into your project name it as index.html, then create the URLRequest using URL object, then passing the request to WKWebView it will load the requested URL into WKWebView.

The Ultimate Guide to WKWebView – Hacking with Swift, Loading local content​​ WKWebView can load any HTML stored in your app bundle using its loadFileURL() method. You should provide this with a URL to some HTML file that you know is in your bundle, along with another URL that stores any other files you want to allow the web view to read. That url. Loading A Web Page In WKWebView. The WKWebView class can be used to display interactive web content in your iOS app, much like an in-app browser. It’s part of the WebKit framework and WKWebView uses the same browser engine as Safari on iOS and Mac.

Customizing WKWebView in iOS, Essentially, using local html just makes no sense cause it would be more straightforward and performant to use native swift code to generate  If you want to load resources from a particular place, such as JavaScript and CSS files, you can set the baseURL parameter to any URL. This could, for example, be the resource path for your app bundle, which would allow you to use local images and other assets alongside your generated HTML.

Comments
  • Thank you for your answer, but the issue seems to come from jquery, see my edit. Thanks again!
  • @Maxime Now you can try with let path = Bundle.main.resourcePath! + "/html/index.html"
  • I tested just to be sure I didn't miss anything, but it does not solve the problem, as explained in my edit. Thank you again
  • Thank you for your answer, but the issue seems to come from jquery, see my edit. I tried your idea, without success unfortunately :)