ios - 在 WKWebView 中注入(inject)全局对象
<p><p>我正在尝试向 WKWebView 添加一个全局对象,其中加载的 HTML 期望存在某个对象(使用 API)。我有以下设置在加载后启动 HTML。这在以下简单示例中有效,但使用 loadRequest 加载的“真实”内容会失败,并显示“ ReferenceError: Can't find variable”。有人有类似经历吗?</p>
<pre><code>@implementation ViewController
- (void)viewDidLoad {
;
;
}
- (void)setupWebView
{
WKWebViewConfiguration *webConfiguration = [ init];
WKUserContentController *userContentController = [ init];
NSString* jsCode =
@"var TheObject = function() {}; \
TheObject.prototype.sendTheMessage = function() { \
window.webkit.messageHandlers.performAction.postMessage(messageToPost); \
}; \
var theObject = new TheObject();";
WKUserScript *userScript = [ initWithSource:jsCode
injectionTime:WKUserScriptInjectionTimeAtDocumentStart
forMainFrameOnly:NO];
;
[userContentController addScriptMessageHandler:self
name:@"performAction"];
webConfiguration.userContentController = userContentController;
self.webView = [ initWithFrame:self.view.bounds
configuration:webConfiguration];
;
[self.webView loadHTMLString:
@"<body onload='sendMessage()'> \
<script>function sendMessage() { \
theObject.sendTheMessage(); \
} \
</script> \
Attempting to send the message \
</body>" baseURL:nil];
}
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
NSLog(@"%@", message);
}
@end
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>示例和我的生产代码的唯一区别是我加载了要从文件中注入(inject)的 javascript。在这个文件中有一个错字。表明尝试将问题简化为示例代码有助于识别您的愚蠢错误!</p></p>
<p style="font-size: 20px;">关于ios - 在 WKWebView 中注入(inject)全局对象,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/33282040/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/33282040/
</a>
</p>
页:
[1]