There may be times when you want to get the path to a user’s home directory in your Dashboard widget. If, like normal, the widget is located in the user’s local Widgets directory (~/Library/Widgets/), we could extract the path from window.location.href. However, this approach is pretty limited, because it requires the widget to be located somewhere in the user’s home directory. What if, for some reason, the user moves our widget into the main Widgets directory (/Library/Widgets/)? This is unlikely, but it is possible. Also, this approach won’t work when we run the widget in Dashcode, because Dashcode temporarily stores the widget in a system folder that isn’t located in the user’s home directory.
Luckily, there’s a solution…
The following Terminal command will give us the path to the user’s home directory:
echo ~
For example, in my user area, this command returns:
/Users/steve
So, to get the path from within our Dashboard widget, we wrap up the Terminal command in a widget.system call:
widget.system("/bin/echo ~", function() {
var output = this.outputString;
// Output includes a line break that we have to remove
var pathToHome = output.replace("\n", "");
};
Using this approach, we will be able to accurately determine the path to the user’s home directory, regardless of the location of the widget.
