Created
April 24, 2015 04:00
-
-
Save RoyalIcing/97298c70082d7b4c6a2a to your computer and use it in GitHub Desktop.
Easily add scripts from your bundle to a WKUserContentController. Has optional template replacing, specify a dictionary with `sourceReplacements:`.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Created by Patrick Smith on 22/04/2015. | |
// Copyright 2015 Patrick Smith. | |
// Released under the MIT License http://opensource.org/licenses/MIT | |
import Cocoa | |
import WebKit | |
extension WKUserContentController { | |
func addBundledUserScript(scriptNameInBundle: String, injectAtStart: Bool = false, injectAtEnd: Bool = false, forMainFrameOnly: Bool = true, sourceReplacements: [String:String]? = nil) { | |
assert(injectAtStart || injectAtEnd, "User script must either be injected at start or at end. Add injectAtStart: true or injectAtEnd: true") | |
let scriptURL = NSBundle.mainBundle().URLForResource(scriptNameInBundle, withExtension: "js")! | |
let scriptSource = NSMutableString(contentsOfURL: scriptURL, usedEncoding: nil, error: nil)! | |
if let sourceReplacements = sourceReplacements { | |
func replaceInTemplate(find target: String, replace replacement: String) { | |
scriptSource.replaceOccurrencesOfString(target, withString: replacement, options: NSStringCompareOptions(0), range: NSMakeRange(0, scriptSource.length)) | |
} | |
for (placeholderID, value) in sourceReplacements { | |
replaceInTemplate(find: placeholderID, replace: value) | |
} | |
} | |
if injectAtStart { | |
let script = WKUserScript(source: scriptSource as String, injectionTime: .AtDocumentStart, forMainFrameOnly: forMainFrameOnly) | |
self.addUserScript(script) | |
} | |
if injectAtEnd { | |
let script = WKUserScript(source: scriptSource as String, injectionTime: .AtDocumentEnd, forMainFrameOnly: forMainFrameOnly) | |
self.addUserScript(script) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment