Reputation: 665
I'm writing a Safari App Extension. In my extension folder I have an HTML file that I would like to read in and append to a web page using Javascript. I can't figure out how to read in the file. I'm open to doing it using Javascript or in the Swift code. Any help would be appreciated, thanks!
Upvotes: 0
Views: 1947
Reputation: 665
I ended up finally figuring out how to do this in the Swift code. I've only been working with Swift a couple days, so this sample may not be great but hopefully it helps:
// The file path below is relative to the root of the extension directory.
let filename: NSString = "folder/file.html" as NSString
let pathExtention = filename.pathExtension
let pathPrefix = filename.deletingPathExtension
if let filepath = Bundle.main.path(forResource: pathPrefix, ofType: pathExtention) {
do {
let contents = try String(contentsOfFile: filepath, encoding: .utf8)
} catch {
// contents could not be loaded
}
}
Upvotes: 0
Reputation: 2829
You can read a text or HTML file with a bit of XMLHttpRequest, like so:
var oReq = new XMLHttpRequest();
oReq.addEventListener('load', function () {
// file contents will be in `this.responseText`;
console.log(this.responseText);
});
oReq.open('GET', 'myfile.html');
oReq.send();
Note that the URL in this example is relative. If you use this code on the global page, it will be relative to the global page. If you use it in an injected script, it will be relative to the web page that you inject the script into, which is not what you want. In this case, you'll need to use an absolute URL that begins with the extension's base URL. To get the base URL, use safari.extension.baseURI
. Here's the 6th line from the above example but using such an absolute URL:
oReq.open('GET', safari.extension.baseURI + 'myfile.html');
A more hacky alternative to using XMLHttpRequest is to load your HTML file in an iframe inside the extension's global page, and then "reading" document.body.innerHTML
of the iframed page from a script on the global page.
Upvotes: 4