stack twitter rss linkedin cross

Wilco van Esch

Skip to main content

Search results

    Access-Control-Allow-Origin header JS issue in Watir

    Problem

    Using Watir to drive a Chrome browser, I found a button was not clickable which was clickable just fine when driving Firefox or when starting Chrome directly rather than through Watir.

    The Chrome Developer Tools console displayed these JS errors:

    No Access-Control-Allow-Origin header present on the requested resource

    Cause

    It looks like Chrome does not trust the POST request the button triggers, since it did not originate from the same domain. In our case that's just because we're testing from localhost.

    Solution

    To do this POST request you'd need to add the Access-Control-Allow-Origin header to the request, but we don't want to muck around with custom requests. Instead, for local testing purposes, we can make Chrome stop enforcing the same-origin policy.

    If you look at the ChromeDriver Capabilities under chromeOptions object, you will see you can feed args into Chrome when starting it.

    The full list of possible arguments you can send along includes --disable-web-security. This sounds dodgy, but is fine for our local testing.

    Using it in Watir

    @browser = Watir::Browser.new :chrome, :switches =>
    ['--disable-websecurity']

    As you can see, the switches have to be provided as an array of strings, even if it's a single value.

    Real life use case

    Before do
    @browser = Watir::Browser.new :chrome, :switches =>
    %w(--ignore-certificate-errors --disable-web-security
    --disable-translate)

    end

    (In Ruby, %w(foo bar) is equivalent to ["foo", "bar"].)