ios - Injecting global object in WKWebView -
i'm attempting add global object wkwebview loaded html expects object present (with api). have following setup prime html after loading. works in following trivial example, 'real' content loaded loadrequest fails "[error] referenceerror: can't find variable". have similar experience?
@implementation viewcontroller - (void)viewdidload { [super viewdidload]; [self setupwebview]; } - (void)setupwebview { wkwebviewconfiguration *webconfiguration = [[wkwebviewconfiguration alloc] init]; wkusercontentcontroller *usercontentcontroller = [[wkusercontentcontroller alloc] init]; nsstring* jscode = @"var theobject = function() {}; \ theobject.prototype.sendthemessage = function() { \ window.webkit.messagehandlers.performaction.postmessage(messagetopost); \ }; \ var theobject = new theobject();"; wkuserscript *userscript = [[wkuserscript alloc] initwithsource:jscode injectiontime:wkuserscriptinjectiontimeatdocumentstart formainframeonly:no]; [usercontentcontroller adduserscript:userscript]; [usercontentcontroller addscriptmessagehandler:self name:@"performaction"]; webconfiguration.usercontentcontroller = usercontentcontroller; self.webview = [[wkwebview alloc] initwithframe:self.view.bounds configuration:webconfiguration]; [self.view addsubview:self.webview]; [self.webview loadhtmlstring: @"<body onload='sendmessage()'> \ <script>function sendmessage() { \ theobject.sendthemessage(); \ } \ </script> \ attempting send message \ </body>" baseurl:nil]; } - (void)usercontentcontroller:(wkusercontentcontroller *)usercontentcontroller didreceivescriptmessage:(wkscriptmessage *)message { nslog(@"%@", message); } @end
the difference example , production code fact loaded javascript injected file. , in file there typo. goes show trying reduce problem down example code helps identify silly mistakes!
Comments
Post a Comment