Safari Extension Questions

前端 未结 4 1181
萌比男神i
萌比男神i 2021-02-05 17:43

I\'m in the process of building my first Safari extension--a very simple one--but I\'ve run into a couple of problems. The extension boils down to a single, injected script that

4条回答
  •  隐瞒了意图╮
    2021-02-05 18:25

    EDIT: like you said in your initial post update, the injected script doesn't have the same kind of access that a global HTML page would have. This is my working solution, imagine you want to know the value of setting "foo" in the injected script:

    Injected script code:

    function getMessage(msgEvent) {
    
        if (msgEvent.name == "settingValueIs")
            alert("Value for asked setting is: " + msgEvent.message);
    
    }
    
    safari.self.tab.dispatchMessage("getSettingValue", "foo"); // ask for value
    safari.self.addEventListener("message", getMessage, false); // wait for reply
    

    Global HTML code:

    function respondToMessage(messageEvent) {
    
        if (messageEvent.name == "getSettingValue") {
    
               // getItem("foo");
            var value = safari.extension.settings.getItem(messageEvent.message);
            // return value of foo to injected script
               safari.application.activeBrowserWindow.activeTab.page.dispatchMessage("settingValueIs", value);
    
        } 
    
    }
    
    safari.application.addEventListener("message",respondToMessage,false);
    

    Hope this helps !


    Initial post: I'm having the same 2nd problem as you, I can't access my settings (or secureSettings) from an injected script. In my case the script is loaded after page load, but even that way I can't use safari.extension.settings.

    The only way it works is with a toolbar/button, the HTML behind that element can getItem and setItem as expected.

    My conclusion is that, for some reason, injected scripts can't access settings (actually, they don't even seem to have access to the safari element). Bug or intended feature, that's left to figure out.

提交回复
热议问题