Skip to content

Instantly share code, notes, and snippets.

@Kludex
Created November 15, 2022 07:39
Show Gist options
  • Save Kludex/d30e011853ad09e2d4afdb6e33fac12e to your computer and use it in GitHub Desktop.
Save Kludex/d30e011853ad09e2d4afdb6e33fac12e to your computer and use it in GitHub Desktop.
Inject JS script into ASGI application
from __future__ import annotations
from starlette.datastructures import MutableHeaders
BROWSER_SYNC_SCRIPT =b"<script>console.log('Hi there!');</script>"
class InjectScriptMiddleware:
def __init__(self, app, script: bytes = BROWSER_SYNC_SCRIPT):
self.app = app
self.script = script
async def __call__(self, scope, receive, send):
if scope["type"] != "http":
return await self.app(scope, receive, send)
inject_script = False
async def send_wrapper(message):
nonlocal inject_script
if message["type"] == "http.response.start":
headers = MutableHeaders(raw=message.get("headers", []))
if headers.get("content-type", "").startswith("text/html"):
inject_script = True
headers["content-length"] = str(int(headers["content-length"]) + len(self.script))
elif message["type"] == "http.response.body":
if not message.get("more_body", False) and inject_script:
message["body"] += self.script
await send(message)
return await self.app(scope, receive, send_wrapper)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment