Disabling Javascript in Chrome (-headless) with the help of PHP Webdriver

I am experimenting with using Chrome without JavaScript enabled.

I attempted to disable JavaScript by adding the --disable-javascript command line argument.

I also tried some experimental options:

        $options->setExperimentalOption('prefs', [
            'profile.managed_default_content_settings.javascript' => 2//this method didn't work
            //,'profile.default_content_setting_values.javascript' => 2//this approach also did not work
        ]);

        $capabilities = DesiredCapabilities::chrome();
        $capabilities->setCapability(ChromeOptions::CAPABILITY, $options);

Unfortunately, neither of these methods were successful in disabling JavaScript in Chrome.

My question is: How can I effectively disable JavaScript in Chrome using the Facebook PHP Webdriver?

To verify if JavaScript is indeed disabled, here is a test snippet:

        $this->driver->get('https://www.whatismybrowser.com/detect/is-javascript-enabled');
        return [
            $this->driver->getTitle(),
            $this->driver->findElement(WebDriverBy::cssSelector('.detected_result'))->getText()
        ];

Answer №1

It's just not possible. Check out this informative link here

Attention: Disabling JavaScript is not supported and may cause significant issues with ChromeDriver's functionality. You might only be able to navigate to a webpage at best. This use case is not endorsed, and we will not provide support for it. Marking this as WontFix - ChromeDriver (and most other WebDriver implementations) rely on JavaScript to operate.

Answer №2

If you want to prevent the execution of JavaScript, you can achieve this by adjusting certain preferences:

"webkit.webprefs.javascript_enabled": false
"profile.content_settings.exceptions.javascript.*.setting": 2
"profile.default_content_setting_values.javascript": 2
"profile.managed_default_content_settings.javascript": 2

However, it's important to note that currently this feature is not supported in headless mode. This is because the preferences are not loaded and there isn't a specific command switch available for this functionality.

In the past, disabling JavaScript would cause issues with Selenium since many commands rely on atom scripts injected into the page. This is no longer the case as all commands are now able to run successfully. One thing to consider though is that the text returned may not include content from a <noscript> element (text that is displayed only when JavaScript is disabled). To work around this, you can read the innerText property using either execute_script or get_attribute.

Answer №3

While the traditional headless mode in Chrome doesn't allow disabling JavaScript, there is a more recent version of headless mode that has no such limitations.

Developers at Chromium have recently introduced a second headless mode that operates similarly to regular Chrome.

The updated method: --headless=chrome

The original method: --headless

You can find more information on this update here: https://bugs.chromium.org/p/chromium/issues/detail?id=706008#c36

Now, with the newer headless mode, you have the option to disable JavaScript.

Answer №4

It has been noted by others that disabling JavaScript in Chrome while using headless mode is still not possible.

However, for future reference, here is the method to do so (without using the --headless argument):

        $options = new ChromeOptions();

        $options->setExperimentalOption('prefs', [
            'profile.managed_default_content_settings.javascript' => 2,
        ]);

        $result = DesiredCapabilities::chrome();

        $result->setCapability(
            ChromeOptions::CAPABILITY_W3C,
            // php-webdriver currently has a bug that requires ->toArray()!
            $options->toArray()
        );

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there an easy method to verify if the local storage is devoid of any data?

Query is named aptly; seeking to verify in a conditional statement. ...

Creating custom functions within views using Sencha Touch 2

I'm having trouble creating my own function in Sencha Touch 2 and I keep receiving an error: Uncaught ReferenceError: function22 is not defined The issue seems to be coming from my Position.js file located in the View directory. Ext.define(' ...

Join the geomarkers in two datasets using connecting lines

I am currently developing a leaflet.js map incorporating two distinct sets of JSON data layers stored as js-files. The first dataset comprises the geographical locations of various newsrooms along with their respective IDs, while the second dataset contai ...

Selenium Python: Overcoming Errors in Xpath Loop Element Retrieval

Currently in the process of creating a web scraper specifically for Pinterest. The majority of data has been successfully gathered, however, each pin includes a "see more" button that reveals additional information such as the 'board name' and &a ...

Consecutive AJAX requests triggered by previous response

While there are numerous resources available regarding making synchronous AJAX calls using deferred promises, my specific issue presents a unique challenge. The process I am attempting to facilitate is as follows: Initiate an AJAX call. If the response i ...

Why Injecting the Kernel into a Service in Symfony 2 is a Mistake

I'm trying to retrieve the current app environment in my service. I discovered that I can obtain it from the kernel, but there are concerns about injecting the kernel directly. Can someone clarify why this is seen as a poor practice? Wouldn't ...

Increase the value of (N) in the copied MongoDB file name

Are there any algorithms available to handle incrementing numbers in duplicate filenames? For instance, let's consider a simple collection of documents stored in a file collection: [ { "_id": "612ead8668bfcc4221a788f6" ...

Validation of the existence of a MongoDB user

I'm currently working on implementing a sign-up form using Mongo, Node.js, and Express.js. I've managed to successfully insert a document into the users collection for a new user. However, I now need to set up validation to check if a user alread ...

What is the best way to create a blurred effect on an image during loading, and then transition to a sharp image once it is fully loaded?

I'm currently working on a project where I want the images to display as a blurred preview initially, and then become clear once fully loaded. This is similar to the feature seen on Instagram, where the app shows a blurred image before displaying the ...

While using Selenium with Edge in Python, encountering the error message "sedgedriver.exe unexpectedly terminated. Status code: 1" is a common issue

When executing a Python script using Edge selenium: driver = webdriver.Edge(service=Service(executable_path=EdgeChromiumDriverManager().install())) driver.get(login_url) driver.maximize_window() sleep_val = random.randint(0, 2) time.sleep(sleep_val) driver ...

Validation is performed on the Bootstrap modal form, ensuring that the modal is only loaded after the

In order to provide a better understanding of my website's file structure, I would like to give an overview. The index.php file dynamically adds many pages to my website. Here is the code from index.php: <?php include ('pages/tillBody.php ...

"Local Vue App service functions as expected, but encounters issues when deployed on an Apache

My Vue App runs smoothly on localhost when I run npm run wc. However, once I migrate it to the server, I encounter an error. The error message is as follows: Vue warn]: Unknown custom element: <v-app> - did you register the component correctly? For r ...

Interpret an array of PHP objects using jQuery Ajax

Trying to populate a website with data retrieved from a database through an array of objects using jQuery. For example: <?php function testFunction() { $data = array() $mydata = new stdClass; $mydata->example = 'test'; $data[] = $mydata ...

What is the most effective way to eliminate error messages from the email format checker code?

Recently, I've been working on a code to validate forms using javascript/jquery. One particular issue I encountered was related to checking email format. The problem arose when entering an invalid email - the error message would display correctly. How ...

Select items from object based on a specified array of IDs

I am facing a challenge with my list of objects that each have an array associated with them. For instance, take a look at this example: "-KpvPH2_SDssxZ573OvM" : { "date" : "2017-07-25T20:21:13.572Z", "description" : "Test", "id" : [ { ...

Execute a PHP function using JavaScript/jQuery with AJAX requests

Hello everyone, I am reaching out for assistance with AJAX as I am still quite new to it. Despite the abundance of examples available, I find it challenging to grasp the concept. Specifically, I need help with my validation of a contact form using JavaScri ...

Coming back to the main script after executing a child node script within a parent node script

I am currently facing an issue where I am attempting to invoke a node script from another node script using execSync. Below is the code snippet illustrating my situation: scriptA.js function a () { for(i=0,i<names.length;i++){ var a = 'somes ...

Webstorm encounters difficulties compiling Sass

While attempting to utilize Sass in the Webstorm IDE, I noticed that it is defaulting to Ruby 1.8 (OS Default) instead of my preferred RVM Ruby Version (1.9.x). To address this issue, I tried setting the path for Sass in the Watcher-Configuration: PATH=$ ...

Altering the context of Javascript script execution

I needed to switch the JavaScript execution context from the parent window to the child window. I was able to successfully load my script objects and functions into the child window context, however, I encountered difficulty in making third party libraries ...

Images in PHP emails are not displaying properly in Outlook and Android Gmail

When it comes to sending an email with PHP, I encountered a problem while trying to include images as table backgrounds. Despite following the advice given, the images do not show up when viewing the email in Outlook and the Android Gmail app. Below is th ...