Safari Extension - How to respond to Settings chan

2019-09-13 21:35发布

问题:

I'm currently working on an Extension for Safari 5 and I want to run a listener function whenever Settings changes are made. Apple provides an example for that, but it doesn't work for me. I currently have this listener function in my global html file:

function numberChanged() 
{
     if(event.key == "number")
         alert("Number has changed!");
}

safari.self.addEventListener("change", numberChanged, false);

I hope somebody can help me. Does somebody know what I'm doing wrong?

回答1:

I believe that you need to include ‘event’ as a parameter in your function so it looks like this:

function numberChanged(event) 
{
     if(event.key == "number")
         alert("Number has changed!");
}

however, that said, it’s not working properly for me either (with or without the param), so I might be wrong. Interestingly, every time I change a field or click a button on this stackoverflow form, my alert (similar to yours) IS firing, even though I did not change my setting. totally weird.

update: I got it working, finally. The example that apple provides is just wrong. So there are two parts to the answer. I gave the first part above — you do need to add ‘event’ as a parameter to your function. the second part is that the addeventlistener has to be done on the settings object and not, as apple shows you, using ‘self’ from the global.html page. so the working call would look like this for you:

safari.extension.settings.addEventListener("change",numberChanged,false);