Search code examples
javascriptmacosmessagejavascript-automation

What is a more elegant way to overcome Error: Expecting object specifier. Argument has no object specifier when sending an SMS via Messages via JXA


This fails to work

    with (Application("Messages")) { 
            send(text, {to: services["SMS"].buddies[phone]}) 
    }

with Error: Expecting object specifier. Argument has no object specifier.

text is valid and not null. phone is valid and not null. If I hard code the values it works. I decided to try 'dynamic' hard coding which worked.

    command = 'with (Application("Messages")) { send("' + text + '", {to: services["SMS"].buddies["' + phone + '"]}) } ;' ;
    eval(command) ;

Is there a more elegant way of overcoming this? Why would eval work but the code with the variables not?


Solution

  • Breaking the code out into smaller pieces helps me.

    var text="foo"
    var phone="+14159999999"
    var Messages = Application('Messages')
    var service = Messages.services[0]
    var recipient = service.buddies.byName(phone, {
        of: service
    })
    
    Messages.send(text  , {
        to: recipient
    })