Path to Script Bundle in JXA?

I’m trying to figure out how to get the path to the current script (actually script bundle) when using Javascript for Automation.

I can do this easily with applescript:

path to me

but with JXA the closest I can get is to the current application (which will work when I compile it, but not before):

Path($.NSBundle.mainBundle.bundlePath.js)

Hi,

NSBundle is part of the Foundation Framework, try this (untested)


ObjC.import('Foundation')
path = $.NSBundle.mainBundle().bundlePath

yeah i tried that, but it doesn’t work.

However, it looks like this should work:


app = Application.currentApplication()
app.includeStandardAdditions = true
pathToResources = app.pathToResource("Scripts")
 

after some research this is the JXA equivalent to path to me

app = Application.currentApplication()
app.includeStandardAdditions = true
pathToMe = app.pathTo(this)

thanks!

This doesn’t work - pathToMe points to the Script Editor app, not the script bundle.

As I understand it, this code worked before, but doesn’t work since Big Sur. The same request is posted on the stack.overflow site.

I would provide a solution, but my account is temporarily blocked there. A well-known bozo has settled there, who does not hesitate to appropriate other people’s answers (solutions). When I was outraged, I was blocked for 1 week. :lol:

@adib, I apologize for the delay in responding. I just wanted to draw attention to the dishonesty of one user from the above site. I was forced to do it here. Against you, I certainly have nothing.

I have Catalina, but if the following solution satisfies you (at Big Sur), then I will be only too glad. Your question is of course about JXA, but I would venture to post the answer here. In order not to tire you and myself by waiting for 3 days (for deblocking my account).

app = Application.currentApplication();
app.includeStandardAdditions = true;
pathToMe = app.pathToResource(‘Scripts/main.scpt’).toString();

Thanks, however this doesn’t work in Big Sur.

AppleScript: 2.11 (225)
Browser: Safari 605.1.15
Operating System: macOS 11.4

It doesn’t work as application as well?

Save as application and try following:


app = Application.currentApplication();
app.includeStandardAdditions = true;
pathToMe = app.pathToResource('Scripts/main.scpt').toString();
app.displayDialog(pathToMe)

And what returns following, saved as script bundle:


app = Application.currentApplication();
app.name()

Correctly, it should return undefined