Search code examples
javascriptphotoshopphotoshop-script

Stuck trying to pass value from jsx to js


Working on a photoshop plugin, I need to have the value of the current document's width available in my index.js script.

As far as I know, I can only get the value in my index.jsx document using the following code:

var mywidth = app.activeDocument.width;

Is there any way of getting the same value from within my index.js file? If not, is there any way of passing the value from my index.jsx file back to the index.js file?

As some people have already suggested in previous questions I've asked on here, I have tried my best to use the tips described in Davide Barranca's article here: https://www.davidebarranca.com/2014/02/html-panels-tips-5-passing-objects-from-jsx-to-html-json/

But for some reason I just can't get it working.


Solution

  • First, you need to load file CSInterface.js in your panel. Make sure that you downloaded this file and your path to this file is correct.

    var csInterface = new CSInterface();
    

    Then you can use evalScript method.

    csInterface.evalScript()
    

    First argument is string to eval and second argument is callback because script might take some time and you don't want to frozen panel UI until script is done. Callback has variable which is result of your JSX code in string.

    csInterface.evalScript('app.activeDocument.width.as("px")',function(result){
        alert(result)
    });
    

    You will get back width in units according units you have in Photoshop settings. Therefore you can specify conversion to pixels. Anyway it won't work if your document units is percentage. In this case you need to change units in advance.