Selaa lähdekoodia

Merge pull request #2191 from zauberzeug/add_html

Allow setting head and body HTML when client is already connected
Rodja Trappe 1 vuosi sitten
vanhempi
säilyke
550251ac67
2 muutettua tiedostoa jossa 17 lisäystä ja 2 poistoa
  1. 2 2
      nicegui/functions/html.py
  2. 15 0
      tests/test_add_html.py

+ 2 - 2
nicegui/functions/html.py

@@ -15,7 +15,7 @@ def add_head_html(code: str, *, shared: bool = False) -> None:
     else:
         client = context.get_client()
         if client.has_socket_connection:
-            raise RuntimeError('Cannot add head HTML after the page has been sent to the client.')
+            client.run_javascript(f'document.head.insertAdjacentHTML("beforeend", {code!r});')
         client._head_html += code + '\n'  # pylint: disable=protected-access
 
 
@@ -32,5 +32,5 @@ def add_body_html(code: str, *, shared: bool = False) -> None:
     else:
         client = context.get_client()
         if client.has_socket_connection:
-            raise RuntimeError('Cannot add body HTML after the page has been sent to the client.')
+            client.run_javascript(f'document.querySelector("#app").insertAdjacentHTML("beforebegin", {code!r});')
         client._body_html += code + '\n'  # pylint: disable=protected-access

+ 15 - 0
tests/test_add_html.py

@@ -0,0 +1,15 @@
+from nicegui import ui
+from nicegui.testing import Screen
+
+
+def test_add_head_html(screen: Screen) -> None:
+    ui.add_head_html(r'<style>.my-label {background: rgb(0, 0, 255)}</style>')
+    ui.label('Label').classes('my-label')
+    ui.button('Green', on_click=lambda: ui.add_head_html(r'<style>.my-label {background: rgb(0, 255, 0)}</style>'))
+
+    screen.open('/')
+    assert screen.find('Label').value_of_css_property('background-color') == 'rgba(0, 0, 255, 1)'
+
+    screen.click('Green')
+    screen.wait(0.5)
+    assert screen.find('Label').value_of_css_property('background-color') == 'rgba(0, 255, 0, 1)'