Search code examples
pythonpython-3.xplotly-dashcytoscape.jscytoscape

Dash Cytoscape data from js script


I'm trying to get node position data from Dash Cytoscape. I found this solution https://community.plotly.com/t/dash-cytoscape-returning-node-positions-from-layout/23818/4 but I can't get data from the browser console in python. How can I do this?


Solution

  • To get data from a js script, you could use a Clientside Callback. As documented here, a clientside callback

    create(s) a callback that updates the output by calling a clientside (JavaScript) function instead of a Python function

    To use it, you can for example write your JavaScript code into Python code like the following:

    from dash import Dash, dcc, html, Input, Output
    
    app = Dash(...)
    
    # Using a Store component and a Button to trigger the callback
    app.layout = html.Div(
        [
            html.Button(id="your-button"),
            dcc.Store(id="js-data")
        ]
    )
    
    app.clientside_callback(
    """
    function (n_clicks) {
        // Insert your JS code here and return
        ...
        return data
    }
    """,
    Output("js-data", "data"),
    Input("your-button", "n_clicks")
    )
    
    @app.callback(
        Output("..."),  # This depends on your application
        Input("js-data", "data")
    )
    def work_with_js(data):
        # Do whatever you want with your data
    

    As you can see, the example uses a Button to trigger the JavaScript code and returns some data in a dcc.Store component. This data is used in another callback afterwards and can be manipulated.