79620098

Date: 2025-05-13 16:54:28
Score: 1.5
Natty:
Report link

I just resolved a similar issue by reading the kAXRoleAttribute of the AXUIElement. I discuss this at length in my answer here. The tl;dr is that I suspect it's a matter of lazy initialization. Reading the role attribute triggers initialization, but adding the observer does not.

Assuming you're facing the same issue, I would try updating your code to the following:

extension pid_t {
    var focussedField: AnyObject? {
        let axUIElementApplication = AXUIElementCreateApplication(self)
        
        // Read and print the application's role field, this seems to triggers initialization of the Accessibility tree. 
        if let role = axUIElementApplication.role() { print("Application Role \(role)") }

        var focussedField: AnyObject?
        let result = AXUIElementCopyAttributeValue(axUIElementApplication, kAXFocusedUIElementAttribute as CFString, &focussedField)
        guard result == .success else {
            logger("Failed to get focussedField \(result.rawValue)", source: .pid)
            Events.PIDExtensionFocusedFieldError(code: result.rawValue).sendEvent()
            return nil
        }
        return focussedField
    }
}

// Add these Accessor helpers too, if you don't already have them!
extension AXUIElement {
    
    func role() -> String? {
        return self.attribute(forAttribute: kAXRoleAttribute as CFString) as? String
    }

    func attribute(forAttribute attribute: CFString) -> Any? {
        var value: CFTypeRef?
        let result = AXUIElementCopyAttributeValue(self, attribute, &value)
        if result == .success {
            return value
        } else {
            return nil
        }
    }
}
Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • Me too answer (2.5): facing the same issue
  • Low reputation (0.5):
Posted by: Tim