When I set JSON data into userInfo, dispatchMessageToScriptWithName:userInfo method doesn't send message to JavaScript.
Safari app extension source code is the following:
(It just sends back data to JavaScript as soon as it receives a message from JavaScript.)
- (void)messageReceivedWithName:(NSString *)messageName fromPage:(SFSafariPage *)page userInfo:(NSDictionary *)userInfo {
// send to JavaScript
NSError *error;
NSData *jsonData ;
NSError *localError;
NSDictionary *resDic = @{
@"logType": @"0",
@"observerMode": @"0",
@"key": @"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
};
@try {
jsonData = [NSJSONSerialization dataWithJSONObject:resDic options:0 error:&localError];
} @catch (NSException *exception) {
NSDictionary *userInfo = @{ @"reason": exception.reason};
localError = [NSError errorWithDomain:@"jp.co.***.SafariAppExtNoDispatch" code:1001 userInfo:userInfo];
} @finally {
if (localError) {
NSLog(@"Data convert error, %@, data=%@", localError, resDic);
error = localError;
return;
}
}
NSDictionary *dic = @{@"res": jsonData };
NSLog(@"[%@ %@] dic%@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), dic);
[page dispatchMessageToScriptWithName:@"message" userInfo:dic];
}
JavaScript is the following:
(It sends a message to the app extension when you visit a site and outputs a log message when JavaScript received a message from the app extension.)
'use strict';
if (window.top === window) {
const html = document.getElementsByTagName("HTML");
console.log("stat to send message by using safari.extension.dispatchMessage:[" + location.href + "]");
document.addEventListener("DOMContentLoaded", function(event) {
safari.extension.dispatchMessage("message",
{BodyRaw: html[0].innerHTML});
});
safari.self.addEventListener('message', hanedleReceivedMessage, false);
function hanedleReceivedMessage(evt) {
console.log("Message received from Extension handler");
}
}
The received message(console log) doesn't appear when I visit any sites.
If I switch JSON data to NSDictionary, it works fine in this simple code. But in the real app, it doesn't work either occasionally.
Does anyone have a workaround or any good idea?
Thanks in advance.