Skip to content

Bind Python Functions and Methods to Javascript in Pytonium

Maximilian Winter edited this page Nov 7, 2022 · 2 revisions

To bind a python function to an javascript call, all we have to do, is to define the function and then call the "bind_function_to_javascript" on the Pytonium instance:

# Let's define a function and bind it to name testfunc in javascript
def testfunc(arg1, arg2, arg3, arg4):
    print([arg1, arg2, arg3, arg4])

pytonium = Pytonium()
# Here we add the actual binding.
pytonium.bind_function_to_javascript("testfunc", testfunc)

pytonium.initialize("C:\TestSite\index.html", 1920, 1080)
...

The method "bind_function_to_javascript" takes two required parameters and one optional, the first parameter is the name which the function is bind to in javascript. The second one is the actual function object. And the third optional parameter is an optional name for a Javascript object, on which the function will be bind.

The example from above would be called like this in javascript:

window.testfunc(42, 24.42, true, 'Hello World!')

When I use the optional third parameter like this:

pytonium.bind_function_to_javascript("testfunc", testfunc, "python_api")

It would be called like this in javascript:

window.python_api.testfunc(42, 24.42, true, 'Hello World!')

You can also bind a python object with its method to javascript like this:

# This class expose three methods as an endpoint of a javascript binding, and they get called on the test website.
class MyApi:

    def __init__(self):
        self.data = []


    @staticmethod
    def TestOne():
        print("Static Python Method called from Javascript!")

    def TestTwo(self, arg1):
        print("Python Method called from Javascript!")
        self.data.append(arg1)
        print(self.data)

    def TestThree(self, arg1, arg2, arg3):
        print("Python Method called from Javascript!")
        self.data.append(arg1)
        self.data.append(arg2)
        self.data.append(arg3)
        print(self.data)



pytonium.bind_object_methods_to_javascript(myApi, "test_binding_python_object_methods")

Here the first parameter is the object to bind and the second is the optional javascript object name.

It would be called like this in Javascript:

 // Call function in python without arguments.
window.test_binding_python_object_methods.TestOne()
// Call function in python with arguments.
window.test_binding_python_object_methods.TestTwo(42)
window.test_binding_python_object_methods.TestThree(24.42, true, 'olleH dlroW!')
Clone this wiki locally