How to Turn Off JavaScript Mid-Session in Kameleo

  • Created

When automating browsers with Kameleo, you might need to disable JavaScript for specific URLs during your session. This can be particularly useful for:

  • Bypassing certain types of detection.
  • Managing resource loading.
  • Controlling script execution on specific pages.

Managing JavaScript Execution

The following method allows you to selectively disable JavaScript for specific URLs using Chrome DevTools Protocol (CDP). The function automatically re-enables JavaScript after navigation (in the finally block).

  • async function manageJavaScriptExecution(driver, url, disableJs = true) {
        try {
            // Check if we are on a URL that should have JavaScript disabled
            if (disableJs) {
                // Disable JavaScript before navigation
                await driver.sendCdpCommand('Emulation.setScriptExecutionDisabled', {
                    value: disableJs
                });
                console.log(`JavaScript ${disableJs ? 'disabled' : 'enabled'} for: ${url}`);
            }
            
            // Navigate to the URL
            await driver.get(url);
            await new Promise(resolve = setTimeout(resolve, 2000)); // Allow time for the page to load
            
        } catch (error) {
            console.error(`Error managing JavaScript execution: ${error}`);
            
        } finally {
            // Re-enable JavaScript after we're done with this URL
            await driver.sendCdpCommand('Emulation.setScriptExecutionDisabled', {
                value: false
            });
        }
    }
  • def manage_javascript_execution(driver, url, disable_js=True):
        try:
            # Check if we are on a URL that should have JavaScript disabled
            if disable_js:
                # Disable JavaScript before navigation
                driver.execute_cdp_cmd('Emulation.setScriptExecutionDisabled', {
                    'value': disable_js
                })
                print(f"JavaScript {'disabled' if disable_js else 'enabled'} for: {url}")
            
            # Navigate to the URL
            driver.get(url)
            time.sleep(2)  # Allow time for the page to load with JS disabled
            
        except Exception as e:
            print(f"Error managing JavaScript execution: {str(e)}")
            
        finally:
            # Re-enable JavaScript after we're done with this URL
            driver.execute_cdp_cmd('Emulation.setScriptExecutionDisabled', {
                'value': False
            })

Key Features

  • Uses Chrome DevTools Protocol (CDP) to toggle JavaScript
  • Automatically re-enables JavaScript after navigation (in the finally block)
  • Includes error handling and logging
  • Provides a clean interface for enabling/disabling JavaScript per URL

Was this article helpful?

0 out of 0 found this helpful