Filling in a div using js code does not trigger Dash callback

Hi there!

We’d like to use a custom js function (that gets a fingerprint of the client machine in order to log how many times they use our app) that returns a string back in a hidden div.

When we do so, the callback that has this div as dcc.Input is not triggered. as far as I can understand, this may be because we perform the operation on the client side while Dash runs on server side, but is there a way to achieve what we want ?

Here is a small piece of code to reproduce what I mean.

import dash
import dash_html_components as html
from dash.dependencies import Input, Output, State

# external JavaScript files
external_scripts = [
    "https://code.jquery.com/jquery-3.2.1.min.js"
]

app = dash.Dash(
    __name__,
    external_scripts=external_scripts,
)

app.layout = html.Div(
    children=[
        html.Div(id="fingerprint"),
        html.Div(id="output")  # We should see the fingerprint appear here when we click
    ]
)

@app.callback(
    Output("output", "children"),
    [Input("fingerprint", "children")],
)
def init_data(fingerprint):
    """Returns the fingerprint value"""
    return f"Received signal: fingerprint is {fingerprint}."

if __name__ == "__main__":
    app.run_server(debug=True)

Here is the custom js code put in assets/custom-script.js:

$(document).ready(function(){
	$("#fingerprint").append("xxxxx");
});

And that’s what happens:

image

while I should see “Received signal: fingerprint is xxxxx.”

Thanks in advance for advice!

In general, using custom JS to interact with the DOM is not going to play well with Dash apps, as in the frontend, the app is a React app, which has it’s own virtual DOM.

You probably need to build the functionality you need into very lightweight Dash component, then you will have full access to whatever JS functions you want.

Thanks @nedned, makes sense! I guess I’ll have to dive into building a custom Dash component.