Hello,
I've been fiddling with safari app extensions and I've found the following issue: While the messages sent from the content scripts are always sent to the background code (Swift in my case) when calling safari.extension.dispatchMessage(), the same cannot be said about the messages sent from the background code to the content scripts: There are some situations where the code reaches the call to the page.dispatchMessageToScript(withName: , userInfo: ), but the message doesn't reach the content scripts (i.e.: the event handler doesn't get called).
From what I've seen, this can happen when doing some back-and-forth navigating between two webpages. I've managed to reproduce this situation with the code bellow.
I've just created the template structure for the Safari App Extension in Xcode. I've then modified the scripts.js file to
document.addEventListener("DOMContentLoaded", function() {
document.addEventListener("keydown", function(event) {
switch (event.key) {
case "ArrowLeft":
window.location.href = "https://www.google.com";
break;
case "ArrowRight":
window.location.href = "https://www.bing.com";
break;
case "ArrowDown":
safari.extension.dispatchMessage('down');
break;
}
});
safari.self.addEventListener("message", function(event) {
if (event.name === 'down') {
console.log("Background code says that the down arrow was pressed");
}
});
});
and the messageReceived method in SafariExtensionHandler to the following:
override func messageReceived(withName messageName: String, from page: SFSafariPage, userInfo: [String : Any]?) {
if (messageName == "down") {
page.dispatchMessageToScript(withName: "down", userInfo: nil)
}
}
Note: I have set the SFSafariWebsiteAccess to All.
The script simply redirects to "www.google.com" when pressing the left arrow key and to "www.bing.com" when pressing the right arrow key. Also, when pressing the down arrow key, a message is sent to the Swift code only to be received back in the event handler and log a message to the browser console. When entering a new webpage in a tab, the down arrow logging works fine. However, if you do a bit of navigating between google and bing by using the arrow keys, the down arrow logging will stop working. And this is because page.dispatchMessageToScript doesn't actually send the message, but the execution still reaches that call. I can't specify exactly how much navigating needs to be done to reproduce the problem as this seems to be somewhat inconsistent.
My operating system is macOS Mojave with Version 10.14.5 (18F203)
My Xcode version is 10.2.1 (10E1001)
My Safari version is 12.1.1 (14607.2.6.1.1)
Note that I'm pretty sure this bug happened with some previous versions of these software aswell.
If you have a chance to test the macOS Catalina beta, it should be fixed there.
You could also try Safari Technology Preview https://developer.apple.com/safari/technology-preview/ to confirm the issue is fixed there (which it should be as well).