What's wrong with this simple Safari Extension code?

javascript, jquery, safari

Solution

The problem is that your extensions Global page does not have direct access to the currently loaded page's DOM. To be able to achieve what you need, you'll have to use an Injected Script and use the messaging proxy to talk to the page.

For instance, your global would look like:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
    <head>
        <script type="text/javascript" src="jquery.js"></script>
    </head>
    <body>
        <script>
            $(document).ready(function() {
                safari.application.addEventListener("command", performCommand, false);
            });

            function performCommand(event) {  
                if (event.command == "open-designs") { 
                    safari.application.activeBrowserWindow.activeTab.page.dispatchMessage("open-designs", "all");
                }  
            }
        </script>
    </body>
</html>

And then, in Extension Builder, you'd need to add two "Start Scripts", one is jquery, the other, a new file that gets loaded into the page and looks similar to this:

function extensionname_openAll(event)
{
    if (event.name == 'open-designs')
    {
        $('a[href*="/Create/DesignProduct.aspx?"]').each(function(index,elem) {
            window.open($(elem).attr('href'),'_blank');
        });
    }
}
safari.self.addEventListener("message", extensionname_openAll, true);

Problem

I'm creating a Safari extension that will stay in Safari's menubar, and upon being clicked, it will open all links containing a certain string. However, it's not working. This is what my extension builder screen looks like: https://i.stack.imgur.com/GSBRw.png I don't have any external scripts set as I have the script in my HTML file, because I only want it to run when clicked. And I have a global.html page with the following code in it: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <script type="text/javascript" src="jquery.js"></script> </head> <body> <script> safari.application.addEventListener("comnand", performCommand, false); Function performCommand(event) { if (event.command == "open-designs") { $(document).ready(function() { $('a[href*="/Create/DesignProduct.aspx?"]').each(function() { window.open($(this).attr('href'),'_blank'); }); }); } } </script> </body> </html> ``` Should this not work? I'm allowed to mix jQuery and JS write, as jQuery is JS? And isn't that how I'd target the links?

Original source