Safari App Extension: JavaScript script is responding to phantom messages

My Safari App Extension is having trouble with one website. This is typical for some other websites as well.

Navigating to that website results in 6 “Load” events. For each such event I send a “safari.extension.dispatchMessage” to my objC code.

For the first of these Load messages, my objC code sends a ‘sendMeIcons” message to “safari.self.addEventListener('message', function(event)”. The other 5 Load events are ignored by my objC code and do not send this message.

safari.self.addEventListener('message', function(event) receives sendMeIcons JUST once. Yet, the event handler for this message) is invoked 4 times. The first invocation is correct. The other 3 are spurious.

I have no idea why this is happening.

Here is my objC code

safari.self.addEventListener('message', function(event) { if (event.name === "Load My URL") { console.log('In event listener Load My URL'); ... return; }

if (event.name === "sendMeIcons")
{
    ...        
    if (hrefs.length  <1)    //THIS IS ALWAYS TRUE FOR THIS TEST CASE.
    {
        safari.extension.dispatchMessage("js Found No Icons");
        return;
    }
    else
    {
       ...
        safari.extension.dispatchMessage("IconsReturned",{"urls": arrayOfUrls});
        return;
    }
}

I don't have a clue how to proceed. Any suggestions.

Replies

Does the page you are visiting have multiple frames?

Do you only want this content script to be run on the main frame?

If so, you can do:

if (window.top === window) {

In the content script.