Access javascript module from Button.js_on_click

Hi,
I am trying to import function/variable from js module loaded to HTML document within the js_on_click() function?
Here is a simple code showing what I am trying to achieve.

import panel as pn
html = """
    <head>
        <script type="module" src="my_module.js"></script>
    </head>
    """
btn_js_call = """
        import {function} from 'my_module.js';
        function(); 
    """
btn = pn.widgets.Button(name="test")
btn.js_on_click(code=btn_js_call)

pn.Column(btn, pn.pane.HTML(html)).show()

When I click the button I get an error: “Cannot use import statement outside a module”.
Is it possible somehow to access the model? Or do I need to include it in a different way?

2 Likes

Hi @tomasbym

You can only import inside a module. So you need to refactor something along the lines of

import panel as pn
html = """
<script type="module" type="javascript/text">
    import {function} from 'my_module.js';
    window.myFunction = function
</script>"""
btn_js_call = """window.MyFunction()"""
btn = pn.widgets.Button(name="test")
btn.js_on_click(code=btn_js_call)

pn.Column(btn, pn.pane.HTML(html)).show()
2 Likes

Thank you for your reply. This works fine
T.

1 Like