Figma Support Forum

NaN Values when retrieving postMessage(event.data.pluginMessage) when passed to document.getElementById("element_id").innerHTML

Hello! I’m currently writing a plugin that’ll retrieve and post font values to my UI. It’ll also use this value within another script written within my ui.html document.

The problem however is that I’m getting NaN values once I try to use these values within another script.

Here’s the code snippet for my UI.HTML file:

<c id = "count"></c>

<script>

//Get Font Value from JS file
  onmessage = (event) => {

    //Pass to innerHTML
    document.getElementById("count").innerHTML = event.data.pluginMessage;
    console.log(event.data.pluginMessage);

  }

 </script>



<script>

//Begin TensorFlow Block
async function learnLinear(){

const fontSize = document.getElementById("count").innerHTML;
const parsed = parseInt (fontSize);


const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));

const learningRate = 0.0001;
const optimizer = tf.train.sgd(learningRate);


model.compile({

  loss: 'meanSquaredError',
  optimizer:'sgd'

});


const xs = tf.tensor2d([-1,0,1,2,3,4], [6,1]); //Readable Font Size @ 18 Inches away from Eyes
const ys = tf.tensor2d([-3,-1,1,3,5,7], [6,1]); //Age of User

await model.fit(xs, ys, {epochs: 500});


///Get Font Size Value from Figma, plug to Prediction
// const selection = figma.currentPage.selection["0"].characters;
const prediction = model.predict((tf.tensor2d([parsed], [1,1])));
const value = prediction.dataSync()[0]

console.log ("Prediction",value);
console.log ("Parsed Font Size", parsed);
console.log("Pure FontSize Value", fontSize)
}

learnLinear();

//End TensorFlow Block

</script>

Here’s the code snippet from my Code.JS file:

figma.showUI(__html__);

const selection = figma.currentPage.selection["0"].fontSize;

console.log(figma.currentPage.selection["0"].fontSize);

figma.ui.resize(500, 500)

Console.log works perfectly fine for the first attempt at logging console.log(event.data.pluginMessage) but, within the second script I’ve no luck trying to retrieve the value within it via document.getElementById(“count”).innerHTML;

Is there a better way to approach this? How else can I use postMessage values within other scripts?

Thank you!!

You run learnLinear function immediately after the script is loaded, but at this time there is no value in the HTML element, so it is parsed as NaN. Only at some point after the script start onmessage runs and adds the number to that HTML element.

You can try running learnLinear inside of the onmessage function. And I’m not sure why you are setting and parsing the number from HTML, you can just pass this number as an argument into learnLinear or set it as a global variable.

@Gleb

Gleb, you are a Legend. Thank you so much.

I just put everything under than onMessage function and it worked like a charm.