Skip to main content

tags: [gradio-custom-component, ] title: gradio_htmlinjector short_description: A HTML injector for css and js colorFrom: blue colorTo: yellow sdk: gradio pinned: false app_file: space.py

gradio_htmlinjector

Static Badge

An HTML, JS, and CSS element injector

Installation

pip install gradio_htmlinjector

Usage

import gradio as gr
from gradio_htmlinjector import HTMLInjector

def inject_all_assets():
    """
    This function prepares the payload of CSS, JS, and HTML content.
    It's called by the demo.load() event listener.
    """
    css_code = ""
    js_code = ""
    
    # Define the HTML for a floating popup, initially hidden.
    popup_html = """
    <div id="my-floating-popup" style="display: none; position: fixed; top: 20%; left: 50%; transform: translateX(-50%); z-index: 9999; background: var(--panel-background-fill, white); border: 1px solid var(--border-color-primary); padding: 25px; border-radius: var(--radius-lg); box-shadow: var(--shadow-drop-lg);">
        <h2>Injected HTML Popup</h2>
        <p>This content exists outside the main Gradio layout.</p>
        <br>
        <button class="lg primary svelte-1ixn6qd" onclick="hideElementById('my-floating-popup')">
            Close Me
        </button>
    </div>
    """

    # Load JavaScript helper functions from an external file.
    try:
        with open("custom_script.js", "r", encoding="utf-8") as f:
            js_code += f.read() + "\n"
    except FileNotFoundError as e:
        print(f"Info: 'custom_script.js' file not found: {e}")

    # Load custom styles from an external file.
    try:
        with open("custom_styles.css", "r", encoding="utf-8") as f:
            css_code += f.read() + "\n"
    except FileNotFoundError as e:
        print(f"Info: 'custom_styles.css' file not found: {e}")

    return {"css": css_code, "js": js_code, "body_html": popup_html}


with gr.Blocks() as demo:
    gr.Markdown("# HTMLInjector Component Demo")
    gr.Markdown("This demo uses a custom component to inject a floating HTML popup and its controlling JavaScript.")
    
    html_injector = HTMLInjector()
    
    show_popup_button = gr.Button("Show Injected Popup", variant="primary")
    
    # This intelligent JS snippet solves the race condition.
    # It defines the action to perform, checks if the helper function is ready,
    # and if not, it waits for the custom 'assets-injected' event before proceeding.
    show_popup_js = """
    () => {
        const action = () => showElementById('my-floating-popup');

        if (typeof showElementById === 'function') {
            action();
        } else {
            console.log("[Button Click] Helpers not ready, waiting for 'assets-injected' event...");
            document.addEventListener('assets-injected', action, { once: true });
        }
    }
    """
    
    show_popup_button.click(fn=None, inputs=None, outputs=None, js=show_popup_js)

    demo.load(fn=inject_all_assets, inputs=None, outputs=[html_injector])


if __name__ == '__main__':
    demo.launch()

HTMLInjector

Initialization

name type default description

User function

The impact on the users predict function varies depending on whether the component is used as an input or output for an event (or both).

  • When used as an Input, the component only impacts the input signature of the user function.
  • When used as an output, the component only impacts the return signature of the user function.

The code snippet below is accurate in cases where the component is used as both an input and an output.

def predict(
    value: Any
) -> typing.Optional[typing.Dict[str, str]][
   typing.Dict[str, str][str, str], None
]:
    return value

Metadata

Release files for gradio-htmlinjector 0.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for gradio-htmlinjector 0.0.1
File Size Uploaded Provenance Actions
gradio_htmlinjector-0.0.1.tar.gz 119.9 kB Without provenance Details for gradio_htmlinjector-0.0.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for gradio-htmlinjector 0.0.1
File Interpreter ABI Platform Actions
gradio_htmlinjector-0.0.1-py3-none-any.whl Python 3 none any Details for gradio_htmlinjector-0.0.1-py3-none-any.whl

Total release size: 177.4 kB

Release files / gradio_htmlinjector-0.0.1.tar.gz

Download URL gradio_htmlinjector-0.0.1.tar.gz
Size 119.9 kB
Tags Source
SHA-256 checksum
How to use checksums
65029a987cc14e29f4433c785ff9159641cdf0453163e3a96bc77442f210e109
BLAKE2b-256 checksum
How to use checksums
cfcde5e39419b81defa3d94998619804a1dc09b7194fbf8fb119a7f16e3e9635
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.10.11

Release files / gradio_htmlinjector-0.0.1-py3-none-any.whl

Download URL gradio_htmlinjector-0.0.1-py3-none-any.whl
Size 57.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
934a20a4f3b6283cabbb5a8ed6e81489f7840563334212935bef0c5e823d5557
BLAKE2b-256 checksum
How to use checksums
d4bbe069ec1ab0f8595607478cc46de3f813f3e715bd4b14ef674dd2dfe4bbd0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.10.11

Security for gradio-htmlinjector 0.0.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.0.1 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page