2020-03-20 14:07:44 +11:00
|
|
|
//! A wrapper for `WKWebViewConfiguration`. It aims to (mostly) cover
|
|
|
|
//! the important pieces of configuring and updating a WebView configuration.
|
|
|
|
|
|
|
|
use objc_id::Id;
|
|
|
|
use objc::runtime::Object;
|
|
|
|
use objc::{class, msg_send, sel, sel_impl};
|
|
|
|
|
2020-03-22 10:46:35 +11:00
|
|
|
use crate::foundation::{id, YES, NO, NSString, NSInteger};
|
2020-03-20 14:07:44 +11:00
|
|
|
use crate::webview::enums::InjectAt;
|
|
|
|
|
|
|
|
/// A wrapper for `WKWebViewConfiguration`. Holds (retains) pointers for the Objective-C runtime
|
|
|
|
/// where everything lives.
|
|
|
|
pub struct WebViewConfig {
|
|
|
|
pub objc: Id<Object>,
|
|
|
|
pub handlers: Vec<String>
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Default for WebViewConfig {
|
|
|
|
/// Initializes a default `WebViewConfig`.
|
|
|
|
fn default() -> Self {
|
|
|
|
let config = unsafe {
|
|
|
|
let config: id = msg_send![class!(WKWebViewConfiguration), new];
|
|
|
|
Id::from_ptr(config)
|
|
|
|
};
|
|
|
|
|
|
|
|
WebViewConfig {
|
|
|
|
objc: config,
|
|
|
|
handlers: vec![]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl WebViewConfig {
|
|
|
|
/// Pushes the specified handler name onto the stack, queuing it for initialization with the
|
|
|
|
/// `WKWebView`.
|
|
|
|
pub fn add_handler(&mut self, name: &str) {
|
|
|
|
self.handlers.push(name.to_string());
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Adds the given user script to the underlying `WKWebView` user content controller.
|
|
|
|
pub fn add_user_script(&mut self, script: &str, at: InjectAt, main_frame_only: bool) {
|
|
|
|
let source = NSString::new(script);
|
2020-03-22 10:46:35 +11:00
|
|
|
let at: NSInteger = at.into();
|
2020-03-20 14:07:44 +11:00
|
|
|
|
|
|
|
unsafe {
|
|
|
|
let alloc: id = msg_send![class!(WKUserScript), alloc];
|
2020-03-22 10:46:35 +11:00
|
|
|
let user_script: id = msg_send![alloc, initWithSource:source injectionTime:at forMainFrameOnly:match main_frame_only {
|
2020-03-20 14:07:44 +11:00
|
|
|
true => YES,
|
|
|
|
false => NO
|
|
|
|
}];
|
|
|
|
|
|
|
|
let content_controller: id = msg_send![&*self.objc, userContentController];
|
|
|
|
let _: () = msg_send![content_controller, addUserScript:user_script];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Enables access to the underlying inspector view for `WKWebView`.
|
|
|
|
pub fn enable_developer_extras(&mut self) {
|
|
|
|
let key = NSString::new("developerExtrasEnabled");
|
|
|
|
|
|
|
|
unsafe {
|
|
|
|
let yes: id = msg_send![class!(NSNumber), numberWithBool:YES];
|
|
|
|
let preferences: id = msg_send![&*self.objc, preferences];
|
|
|
|
let _: () = msg_send![preferences, setValue:yes forKey:key];
|
|
|
|
}
|
|
|
|
}
|
2020-03-21 12:37:00 +11:00
|
|
|
|
2020-03-22 10:46:35 +11:00
|
|
|
/// Consumes and returns the underlying `WKWebViewConfiguration`.
|
|
|
|
pub fn into_inner(mut self) -> id {
|
2020-03-21 12:37:00 +11:00
|
|
|
&mut *self.objc
|
|
|
|
}
|
2020-03-20 14:07:44 +11:00
|
|
|
}
|