Skip to content

Conversation

@navin772
Copy link
Member

@navin772 navin772 commented Oct 27, 2025

User description

🔗 Related Issues

💥 What does this PR do?

Adds support for the Emulation module command set_scripting_enabled - https://w3c.github.io/webdriver-bidi/#command-emulation-setScriptingEnabled

🔧 Implementation Notes

💡 Additional Considerations

Not yet supported in Firefox, so marked as xfail.

🔄 Types of changes

  • New feature (non-breaking change which adds functionality and tests!)

PR Type

Enhancement


Description

  • Adds set_scripting_enabled emulation command to disable JavaScript

  • Supports both browsing contexts and user contexts

  • Includes comprehensive validation and error handling

  • Adds two test cases with Firefox xfail markers


Diagram Walkthrough

flowchart LR
  A["Emulation Module"] -->|"set_scripting_enabled()"| B["Disable/Clear JS Override"]
  B -->|"contexts parameter"| C["Apply to Browsing Contexts"]
  B -->|"user_contexts parameter"| D["Apply to User Contexts"]
  C -->|"execute command"| E["WebDriver BiDi Command"]
  D -->|"execute command"| E
Loading

File Walkthrough

Relevant files
Enhancement
emulation.py
Add set_scripting_enabled emulation command                           

py/selenium/webdriver/common/bidi/emulation.py

  • Adds new set_scripting_enabled() method to the Emulation class
  • Implements validation to ensure only disabled JavaScript emulation is
    supported
  • Validates that either contexts or user_contexts is provided, but not
    both
  • Executes the emulation.setScriptingEnabled BiDi command with
    appropriate parameters
+38/-0   
Tests
bidi_emulation_tests.py
Add tests for set_scripting_enabled functionality               

py/test/selenium/webdriver/common/bidi_emulation_tests.py

  • Adds test_set_scripting_enabled_with_contexts() to verify JavaScript
    disabling with browsing contexts
  • Adds test_set_scripting_enabled_with_user_contexts() to verify
    JavaScript disabling with user contexts
  • Both tests verify that scripts don't execute when disabled and execute
    normally after clearing override
  • Both tests marked with @pytest.mark.xfail_firefox due to Firefox not
    yet supporting this feature
+71/-0   

@selenium-ci selenium-ci added C-py Python Bindings B-devtools Includes everything BiDi or Chrome DevTools related labels Oct 27, 2025
@qodo-merge-pro
Copy link
Contributor

qodo-merge-pro bot commented Oct 27, 2025

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
🟢
No security concerns identified No security vulnerabilities detected by AI analysis. Human verification advised for critical code.
Ticket Compliance
🟡
🎫 #1234
🔴 Provide a fix or workaround ensuring click() triggers JavaScript href handlers
consistently.
Investigate and address JavaScript in link href not triggering on click() in Firefox
around versions 42 with Selenium 2.48.x compared to 2.47.1.
Verify behavior with Firefox and document/test the change.
🟡
🎫 #5678
🔴 Provide a resolution to prevent connection failures on subsequent ChromeDriver
instantiations.
Diagnose "Error: ConnectFailure (Connection refused)" when instantiating multiple
ChromeDriver instances on Ubuntu 16.04.4 with Selenium 3.9.0 and Chrome 65/ChromeDriver
2.35.
Add tests or documentation verifying stability across multiple instances.
Codebase Duplication Compliance
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status: Passed

Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status: Passed

Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status: Passed

Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status: Passed

Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status: Passed

Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status:
No action logs: The new emulation command execution and state changes are not logged, making it unclear
who disabled/enabled scripting and where it was applied.

Referred Code
def set_scripting_enabled(
    self,
    enabled: Union[bool, None] = False,
    contexts: Optional[list[str]] = None,
    user_contexts: Optional[list[str]] = None,
) -> None:
    """Set scripting enabled override for the given contexts or user contexts.

    Parameters:
    -----------
        enabled: False to disable scripting, None to clear the override.
                Note: Only emulation of disabled JavaScript is supported.
        contexts: List of browsing context IDs to apply the override to.
        user_contexts: List of user context IDs to apply the override to.

    Raises:
    ------
        ValueError: If both contexts and user_contexts are provided, or if neither
                   contexts nor user_contexts are provided, or if enabled is True.
    """
    if enabled:


 ... (clipped 16 lines)
  • Update
Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

@qodo-merge-pro
Copy link
Contributor

qodo-merge-pro bot commented Oct 27, 2025

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Allow global scripting override setting

Remove the check that prevents applying set_scripting_enabled globally. The
current implementation requires either contexts or user_contexts, but omitting
both should apply the setting globally, consistent with other emulation methods.

py/selenium/webdriver/common/bidi/emulation.py [314-315]

-if contexts is None and user_contexts is None:
-    raise ValueError("Must specify either contexts or userContexts")
+# This block is removed to allow global overrides.
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies that the new method set_scripting_enabled is inconsistent with other similar methods in the class, which allow for global application by omitting context arguments. Removing the check improves consistency and functionality.

Medium
Learned
best practice
Make enabled validation explicit

Explicitly validate that enabled is either False or None and raise a clear error
for other types/values, avoiding truthiness checks that accept non-bool truthy
values.

py/selenium/webdriver/common/bidi/emulation.py [288-309]

 def set_scripting_enabled(
     self,
     enabled: Union[bool, None] = False,
     contexts: Optional[list[str]] = None,
     user_contexts: Optional[list[str]] = None,
 ) -> None:
+    # Only False (disable) or None (clear) are supported
+    if enabled not in (False, None):
+        raise ValueError("Only emulation of disabled JavaScript is supported (enabled must be False or None)")
     ...
-    if enabled:
-        raise ValueError("Only emulation of disabled JavaScript is supported (enabled must be False or None)")

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 6

__

Why:
Relevant best practice - Validate inputs and states early with precise checks, ensuring argument types and allowed values are explicit and consistent.

Low
  • Update

@navin772 navin772 requested a review from cgoldberg October 27, 2025 11:26
Copy link
Member

@cgoldberg cgoldberg left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM.

tiny nitpick: we are trying to standardize docstrings to use Google format: https://github.com/google/styleguide/blob/gh-pages/pyguide.md#38-comments-and-docstrings

... so use Args: instead of Paramaters: and remove the ------.

@navin772
Copy link
Member Author

I have formatted the emulation module to use google format, I see we have an open PR that addresses this for other modules.

@navin772 navin772 merged commit 2e0d0e5 into SeleniumHQ:trunk Oct 28, 2025
21 of 22 checks passed
@navin772 navin772 deleted the py-bidi-scrpting_enabled branch October 28, 2025 07:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

B-devtools Includes everything BiDi or Chrome DevTools related C-py Python Bindings Review effort 2/5

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants