How to dynamically change contextual menu items?

I’m developing a Safari App Extension. My goal would be that to have an item added to the contextual menu ONLY if certain conditions are satisfied. In particular I would like to have my item appear only when right clicking on a specific type of HTML element.


I know how to add an item to the contextual menu, by defyining it in the Info.plist of my extension.

I know how to detect if the contextual menu will appear, in the JavaScript code of my extension.

I also know how to check if my desired condition is satisfied or not.

But I don’t know how to prevent my item from appearing in the contextual menu. Is it possible to do?

Accepted Reply

Yes. I recently converted my Safari extension. And in Swift you can use this to hide the context menu



override func validateContextMenuItem(withCommand command: String, in page: SFSafariPage, userInfo: [String : Any]? = nil, validationHandler: @escaping (Bool, String?) -> Void) {

if(command == "yourcommandtext"){

//show

validationHandler(false, nil)

}

else{
//hide

validationHandler(true, nil)

}

}

}

Replies

Yes. I recently converted my Safari extension. And in Swift you can use this to hide the context menu



override func validateContextMenuItem(withCommand command: String, in page: SFSafariPage, userInfo: [String : Any]? = nil, validationHandler: @escaping (Bool, String?) -> Void) {

if(command == "yourcommandtext"){

//show

validationHandler(false, nil)

}

else{
//hide

validationHandler(true, nil)

}

}

}

Thanks, this should do the job.


Unfortunately i can’t use this function because I’m using an old version of Xcode, since I can’t update my Mac further than macOS 10.11.6, and this is only available since the SDK for 10.12.4+. I guess I’ll have to get my hands on a newer Mac before releasing the extension. Nonetheless, thanks again.