How can I make a new Image in Pages with JXA?

Hi there!


I'm trying insert a new image in a Pages document with Javascript JXA.


In AppleScript work properly:

tell application id "com.apple.iWork.Pages"

activate

if not (exists document 1) then error number -128

tel document 1

tell page 1

set targetImageFilePath to "/Users/gasparekferenc/Documents/GitHub/OSX-Automation/AKG-189060_samples.jpg"

set targetImageFile to targetImageFilePath as POSIX file

set thisImage to make new image with properties {file:targetImageFile, width:100, height:100, position:{100, 100}}

end tell

end tell

end tell


But, I could't found the right systax in JXA.


app = Application('Pages');

doc = app.documents[0]

fn = "/Users/gasparekferenc/Documents/GitHub/OSX-Automation/AKG-189060_samples.jpg"

f = Path(fn).toString();

img = doc.Image.make({file:f,width:100,height:100,position:{x:100,y: 100}});



What"s the wrong?

Could enyone help me?

JXA is what’s wrong. Buggy, broken, obfuscated, abandoned garbage that failed so hard, Apple fired the product manager and disbanded the entire Mac Automation department.


Honestly, the only good answer I can give you is: Stick to AppleScript. Lousy language, but its automation support works right.


..


If you’re really determined to use JXA then you will need to write something like:


var img = app.Image({file:f,width:100,height:100,position:{x:100,y: 100}})

doc.pages[0].push(img)


That’s off the top of my head though, so might not be 100% right. Here’s Apple’s full [cough] JXA documentation if you want to go check for the exact incantation:


https://developer.apple.com/library/content/releasenotes/InterapplicationCommunication/RN-JavaScriptForAutomation/Articles/OSX10-10.html


Complete nonsense that deliberately deceives its users about what’s actually going on, but its developers must’ve thought it’d be a really clever idea to pretend Apple event IPC works just like DOM. (It doesn’t, it wasn’t, it worked just as badly the first time they tried it, and you’re far from first to be flummoxed by it. Ironic too seeing how JSers themselves hate working with DOM’s low-level OO APIs; hence the huge popularity of jQuery which, like Apple event IPC, is query-powered instead.)


HTH

--


p.s. If you’re curious how a professional-quality Apple event bridge should work:


https://www.npmjs.com/package/nodeautomation


though please be aware I won’t provide any maintenance or support for it. (It should still work, but you’re on your own if you choose to use it.)

How can I make a new Image in Pages with JXA?
 
 
Q