Web Development and Testing

How to test run Javascript on browsers without a server job by disabling CORS policy

Disable Browser's CORS policy. Access local files from browser

Introduction

In order to prevent cross site scripting (XSS), for security reasons, browsers restrict cross-origin HTTP request. Hence web applications using fetch() and XMLHttpRequest can only request resources from same origin the application was loaded from. (except response from origins includes appropriate CORS headers). This makes developers not able to test run javascript with fetch and XMLHttpRequests from their local system for development purpose. They have to use the live preview like options using their IDEs (Integrated Development Environements).

Chromium / Google Chrome CORS options

Chromium and Google chrome browser has undocumented browser options / flags that could be used to override the CORS policy. This reduces the security protection of the browser. Developers can test javascript directly from their local system. This doesnt requrie any localhost server program running.

Disabling CORS and local file access restrictions in Google Chrome for development purposes can be done by launching Chrome with the following command-line arguments. This helps to create a separate instance of Chrome with reduced security for for testing.

Setup Steps

1Close all the instances of Chromium / Google Chrome
2Enter the following command on the terminal to launch chrome(ium) with CORS policy disabled.

Linux

Command line snapshot
Command line snapshot

Before Chrome 48, you could just use the following command.

Windows

Mac

3In the browser url box, enter the location of the html file which contains javascript that needs to be tested using the local file URL. Linux eg:

Explanation

  • --disable-web-security:

    disables the Same-Origin Policy, effectively bypassing CORS restrictions and allowing cross-origin requests

  • --user-data-dir="[path]":

    specifies a separate directory for user data, ensuring that your main Chrome profile remains untouched and preventing potential conflicts from running with reduced security. Replace [path] with a suitable location on your system.

  • --allow-file-access-from-files:

    to access local files for dev purposes like AJAX or JSON

  • --disable-features=IsolateOrigins,site-per-process:

    to access cross-origin frames.

See Also

MDN : How do you set up a local testing server?


References: