Execute JavaScript expression in the user's browser and get the value of the expression :param str expression_: JavaScript expression. The value of the expression need to be JSON-serializable. If the value of the expression is a `promise <https://developer.mozilla.org/en-US/docs/Web/Java
(expression_, **args)
| 356 | |
| 357 | @chose_impl |
| 358 | def eval_js(expression_, **args): |
| 359 | """Execute JavaScript expression in the user's browser and get the value of the expression |
| 360 | |
| 361 | :param str expression_: JavaScript expression. The value of the expression need to be JSON-serializable. |
| 362 | If the value of the expression is a `promise <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise>`_, |
| 363 | ``eval_js()`` will wait for the promise to resolve and return the value of it. When the promise is rejected, `None` is returned. |
| 364 | :param args: Local variables passed to js code. Variables need to be JSON-serializable. |
| 365 | :return: The value of the expression. |
| 366 | |
| 367 | Note: When using :ref:`coroutine-based session <coroutine_based_session>`, |
| 368 | you need to use the ``await eval_js(expression)`` syntax to call the function. |
| 369 | |
| 370 | Example: |
| 371 | |
| 372 | .. exportable-codeblock:: |
| 373 | :name: eval_js |
| 374 | :summary: `eval_js()` usage |
| 375 | |
| 376 | current_url = eval_js("window.location.href") |
| 377 | put_text(current_url) # ..demo-only |
| 378 | |
| 379 | ## ---- |
| 380 | function_res = eval_js('''(function(){ |
| 381 | var a = 1; |
| 382 | a += b; |
| 383 | return a; |
| 384 | })()''', b=100) |
| 385 | put_text(function_res) # ..demo-only |
| 386 | |
| 387 | ## ---- |
| 388 | promise_res = eval_js('''new Promise(resolve => { |
| 389 | setTimeout(() => { |
| 390 | resolve('Returned inside callback.'); |
| 391 | }, 2000); |
| 392 | });''') |
| 393 | put_text(promise_res) # ..demo-only |
| 394 | |
| 395 | .. versionchanged:: 1.3 |
| 396 | |
| 397 | The JS expression support return promise. |
| 398 | """ |
| 399 | |
| 400 | from ..io_ctrl import send_msg |
| 401 | send_msg('run_script', spec=dict(code=expression_, args=args, eval=True)) |
| 402 | |
| 403 | res = yield next_client_event() |
| 404 | assert res['event'] == 'js_yield', "Internal Error, please report this bug on " \ |
| 405 | "https://github.com/wang0618/PyWebIO/issues" |
| 406 | return res['data'] |
| 407 | |
| 408 | |
| 409 | @check_session_impl(CoroutineBasedSession) |
no test coverage detected
searching dependent graphs…