Run python code from javascript Jupyterlab

Hi,

I am able to run python code from Javascript using Jupyterapp. But it is not working like I want.

  1. Enabled jupyterapp c.LabApp.expose_app_in_browser = True
  2. Running the following code to get cookies from the browser
from IPython.display import display, Javascript
js_code = """
async function run() {
    const session = jupyterapp.shell.currentWidget.context.sessionContext.session;
    const kernel = jupyterapp.serviceManager.sessions._connectToKernel({model: {id: session._kernel._id, name: session._kernel._name}})
    const cookies = document.cookie.split(';').reduce((acc, cookie) => {
        const [name, value] = cookie.trim().split('=');
        acc[name] = value;
        return acc;
    }, {});
    await kernel.requestExecute({code: `
    globals()["access"] = ` + `'${cookies.access}';
    globals()["refresh"] = ` + `'${cookies.refresh}';
    `}).done;
    console.log("executed")
}

run()
"""
display(Javascript(js_code))
print(globals()['access'])
print(globals()['refresh'])

Now I am not getting the global() variables access after display function. After sometime, if I print those variables in a new cell it is working. But in the same cell it throws KeyError even after time.sleep.

Is there any better way to do it?