Adding third-party cookie exception to Cypress configuration - javascript

Using Cypress, JavaScript end to end testing framework, is there a supported mechanism to add a third-party cookie exception, or some other Chromium preference (or Electron/ if not using e.g. --browser chromium)?
I have found a mechanism to do this but it involves wrapping the browser executable, effectively a man-in-the-middle between Cypress and the "browser" binary.

Presently, Cypress does not provide direct support for this. There is a standing change request to provide API support for this and other Chromium/browser preferences: https://github.com/cypress-io/cypress/issues/3671
A solution I've created is to run Cypress with a custom browser which pre-populates the Chromium user data directory ("profile") with these preferences: https://github.com/cypress-io/cypress/issues/3671#issuecomment-549660119
#!/usr/bin/env bash
USER_DATA_DIR=`cut -d "=" -f 2 <<< ${*: -2:1}`
mkdir $USER_DATA_DIR/Default > $USER_DATA_DIR/Default/Preferences
cat << END_Preferences > $USER_DATA_DIR/Default/Preferences
{
"profile":{"content_settings":{"exceptions":{"cookies":{"example.com,*":{"setting":1}}}}}
}
END_Preferences
exec chromium $#

Related

CORS policy error on file in same folder as HTML [duplicate]

I am getting the following error:
XMLHttpRequest cannot load file:///C:/Users/richa.agiwal/Desktop/get/rm_Library/templates/template_viewSettings.html. Cross origin requests are only supported for HTTP.
I realize that this question has been answered before, but I still have not found a solution to my problem. I tried running chrome.exe --allow-file-access-from-files from the command prompt, and moved the file to the local file system, but I still get the same error.
I appreciate any suggestions!
If you are doing something like writing HTML and Javascript in a code editor on your personal computer, and testing the output in your browser, you will probably get error messages about Cross Origin Requests. Your browser will render HTML and run Javascript, jQuery, angularJs in your browser without needing a server set up. But many web browsers are programed to watch for cross site attacks, and will block requests. You don't want just anyone being able to read your hard drive from your web browser. You can create a fully functioning web page using Notepad++ that will run Javascript, and frameworks like jQuery and angularJs; and test everything just by using the Notepad++ menu item, RUN, LAUNCH IN FIREFOX. That's a nice, easy way to start creating a web page, but when you start creating anything more than layout, css and simple page navigation, you need a local server set up on your machine.
Here are some options that I use.
Test your web page locally on Firefox, then deploy to your host.
or: Run a local server
Test on Firefox, Deploy to Host
Firefox currently allows Cross Origin Requests from files served from your hard drive
Your web hosting site will allow requests to files in folders as configured by the manifest file
Run a Local Server
Run a server on your computer, like Apache or Python
Python isn't a server, but it will run a simple server
Run a Local Server with Python
Get your IP address:
On Windows: Open up the 'Command Prompt'. All Programs, Accessories, Command Prompt
I always run the Command Prompt as Administrator. Right click the Command Prompt menu item and look for Run As Administrator
Type the command: ipconfig and hit Enter.
Look for: IPv4 Address . . . . . . . . 12.123.123.00
There are websites that will also display your IP address
If you don't have Python, download and install it.
Using the 'Command Prompt' you must go to the folder where the files are that you want to serve as a webpage.
If you need to get back to the C:\ Root directory - type cd/
type cd Drive:\Folder\Folder\etc to get to the folder where your .Html file is (or php, etc)
Check the path. type: path at the command prompt. You must see the path to the folder where python is located. For example, if python is in C:\Python27, then you must see that address in the paths that are listed.
If the path to the Python directory is not in the path, you must set the path. type: help path and hit Enter. You will see help for path.
Type something like: path c:\python27 %path%
%path% keeps all your current paths. You don't want to wipe out all your current paths, just add a new path.
Create the new path FROM the folder where you want to serve the files.
Start the Python Server: Type: python -m SimpleHTTPServer port Where 'port' is the number of the port you want, for example python -m SimpleHTTPServer 1337
If you leave the port empty, it defaults to port 8000
If the Python server starts successfully, you will see a msg.
Run You Web Application Locally
Open a browser
In the address line type: http://your IP address:port
http://xxx.xxx.x.x:1337 or http://xx.xxx.xxx.xx:8000 for the default
If the server is working, you will see a list of your files in the browser
Click the file you want to serve, and it should display.
More advanced solutions
Install a code editor, web server, and other services that are integrated.
You can install Apache, PHP, Python, SQL, Debuggers etc. all separately on your machine, and then spend lots of time trying to figure out how to make them all work together, or look for a solution that combines all those things.
I like using XAMPP with NetBeans IDE. You can also install WAMP which provides a User Interface for managing and integrating Apache and other services.
Simple Solution
If you are working with pure html/js/css files.
Install this small server(link) app in chrome. Open the app and point the file location to your project directory.
Goto the url shown in the app.
Edit: Smarter solution using Gulp
Step 1: To install Gulp. Run following command in your terminal.
npm install gulp-cli -g
npm install gulp -D
Step 2: Inside your project directory create a file named gulpfile.js. Copy the following content inside it.
var gulp = require('gulp');
var bs = require('browser-sync').create();
gulp.task('serve', [], () => {
bs.init({
server: {
baseDir: "./",
},
port: 5000,
reloadOnRestart: true,
browser: "google chrome"
});
gulp.watch('./**/*', ['', bs.reload]);
});
Step 3: Install browser sync gulp plugin. Inside the same directory where gulpfile.js is present, run the following command
npm install browser-sync gulp --save-dev
Step 4: Start the server. Inside the same directory where gulpfile.js is present, run the following command
gulp serve
To add to Alan Wells's elaborate answer here is a quick fix
Run a Local Server
you can serve any folder in your computer with Serve
First, navigate using the command line into the folder you'd like to serve.
Then
npx i -g serve
serve
or if you'd like to test Serve without downloading it
npx serve
and that's it! You can view your files at http://localhost:5000
If you are using vscode, you can easily start a liver server. Click liver server at the bottom of the page, once the server is started, vscode will tell the port the project is running. Do ensure your project folder is the workspace
This error is happening because you are just opening html documents directly from the browser. To fix this you will need to serve your code from a webserver and access it on localhost. If you have Apache setup, use it to serve your files. Some IDE's have built in web servers, like JetBrains IDE's, Eclipse...
If you have Node.Js setup then you can use http-server. Just run npm install http-server -g and you will be able to use it in terminal like http-server C:\location\to\app.
Kirill Fuchs
If you use the WebStorm Javascript IDE, you can just open your project from WebStorm in your browser. WebStorm will automatically start a server and you won't get any of these errors anymore, because you are now accessing the files with the allowed/supported protocols (HTTP).
I was facing this error while I deployed my Web API project locally and I was calling API project only with this URL given below:
localhost//myAPIProject
Since the error message says it is not http:// then I changed the URL and put a prefix http as given below and the error was gone.
http://localhost//myAPIProject
Depends on your needs, but there is also a quick way to temporarily check your (dummy) JSON by saving your JSON on http://myjson.com. Copy the api link and paste that into your javascript code. Viola! When you want to deploy the codes, you must not forget to change that url in your codes!

Docker/Selenium/Headless Chrome: Configure SUID sandbox correctly

I want to run selenium and headless chrome in my docker container for testing purpose.
I have tried to run selenium in headless chrome (outside my docker container) with the following in my .js file. This worked:
const client = webdriverio.remote({
desiredCapabilities: {
browserName: 'chrome',
chromeOptions: {
args: ['--headless', '--disable-gpu']
},
binary: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
},
baseUrl: CONFIG.host,
logLevel: 'verbose',
waitForTimeout: 3000
})
But I can't get this to work in my docker container. In my docker container I use "FROM selenium/standalone-chrome". There does not seem to be any problem with my dockerfile. The problem occurs when I try to run my selenium tests. I changed the binary_path in my .js file to /opt/google/chrome/google-chrome. But the tests fails and client can not even be initiated.
So I tried to just run /opt/google/chrome/google-chrome in order to see if chrome works, but then I get this error:
[0711/005304.226472:ERROR:nacl_helper_linux.cc(311)] NaCl helper
process running without a sandbox!
Most likely you need to configure your SUID sandbox correctly
I am pretty new to this (and stack overflow) so there might be some basic things I have missed.
Try to include --no-sandbox
chromeOptions: {
args: ['--headless', '--disable-gpu', '--no-sandbox']
},
As I'm doing at docker-selenium
This error message...
[1003/144118.702053:ERROR:nacl_helper_linux.cc(310)] NaCl helper process running without a sandbox!
Most likely you need to configure your SUID sandbox correctly
...implies that you have no setuid sandbox in your system, hence the program was unable to initiate/spawn a new Browsing Context i.e. Chrome Browser session.
Solution
The easiest (not so clean) solution is, if you want to run Chrome and only use the namespace sandbox, you can set the flag:
--disable-setuid-sandbox
This flag will disable the setuid sandbox (Linux only). But if you do so on a host without appropriate kernel support for the namespace sandbox, Chrome will not spin up. As an alternative you can also use the flag:
--no-sandbox
This flag will disable the sandbox for all process types that are normally sandboxed.
Example:
chromeOptions: {
args: ['--disable-setuid-sandbox', '--no-sandbox']
},
You can find a detailed discussion in Security Considerations - ChromeDriver - Webdriver for Chrome
Deep dive
As per the documentation in Linux SUID Sandbox Development google-chrome needs a SUID helper binary to turn on the sandbox on Linux. In majority of the cases you can install the proper sandbox for you using the command:
build/update-linux-sandbox.sh
This program will install the proper sandbox for you in /usr/local/sbin and tell you to update your .bashrc if required.
However, there can be some exceptions as an example, if your setuid binary is out of date, you will get messages such as:
NaCl helper process running without a sandbox!
Most likely you need to configure your SUID sandbox correctly
Or
Running without the SUID sandbox!
In these cases, you need to:
Build chrome_sandbox whenever you build chrome (ninja -C xxx chrome chrome_sandbox instead of ninja -C xxx chrome)
After building, execute update-linux-sandbox.sh.
# needed if you build on NFS!
sudo cp out/Debug/chrome_sandbox /usr/local/sbin/chrome-devel-sandbox
sudo chown root:root /usr/local/sbin/chrome-devel-sandbox
sudo chmod 4755 /usr/local/sbin/chrome-devel-sandbox
Finally, you have to include the following line in your ~/.bashrc (or .zshenv):
export CHROME_DEVEL_SANDBOX=/usr/local/sbin/chrome-devel-sandbox

How to use a browser on a remote server for an automated tests

I inherited a project where the person wrote tools to test our site's UI using JQuery and JS.
I don't know too much about it other than it requires a browser to be spawned and I think the tool uses JS to interact with iframes to see if it's the expected values.
My job is to get this tool to run on a remote server and post the results to Jenkins.
The remote test server and staging server is linux. From our staging server, I want to write a script to spawn a browser and run cmds from the tool to test our UI. I ran the following manually:
ssh -X user#remote_test_server /usr/bin/firefox
However, the remote server says:
Error: no display specified
Is there a way to spawn a browser for automated testing from one headless server to another? Thanks in advance for your help.
I faced a similar problem when I tried to automate a GUI installation program. While there are quite some different possibilities to choose from (e.g. Xnest, Xephyr?), I ended up using vncserver, because it's relatively easy to debug the GUI session this way.
You need to create a vncpassword file, I think:
mkdir -p $HOME/.vnc
chmod 0700 $HOME/.vnc
echo MyLittlePassword | vncpasswd -f > $HOME/.vnc/passwd
chmod 0600 $HOME/.vnc/passwd
Starting the server is then quite straightforward
vncserver
export DISPLAY=:1
/usr/bin/firefox&
...
Now it is possible to connect to the VNC server with a VNC viewer of your choice. But beware there may be no window manager, depending on the X startup scripts of your environment.
Shutting the server down
vncserver -kill :1
In the configuration of Jenkins project , specify the
Build Environment
Start Xvfb before the build, and shut it down after.
#

How to launch html using Chrome at "--allow-file-access-from-files" mode?

I have the same situation with HERE
And to solve this problem I have to launch html file using Chrome at "--allow-file-access-from-files" mode.
I tried next steps many times, but it doesn't work.
start cmd under windows 7
direct to chrome.exe folder
do this chrome --allow-file-access-from-files file:///C:/test%20-%203.html
That flag is dangerous!! Leaves your file system open for access. Documents originating from anywhere, local or web, should not, by default, have any access to local file:/// resources.
Much better solution is to run a little http server locally.
--- For Windows ---
The easiest is to install http-server globally using node's package manager:
npm install -g http-server
Then simply run http-server in any of your project directories:
Eg. d:\my_project> http-server
Starting up http-server, serving ./
Available on:
http:169.254.116.232:8080
http:192.168.88.1:8080
http:192.168.0.7:8080
http:127.0.0.1:8080
Hit CTRL-C to stop the server
Or as prusswan suggested, you can also install Python under windows, and follow the instructions below.
--- For Linux ---
Since Python is usually available in most linux distributions, just run python -m SimpleHTTPServer in your project directory, and you can load your page on http://localhost:8000
In Python 3 the SimpleHTTPServer module has been merged into http.server, so the new command is python3 -m http.server.
Easy, and no security risk of accidentally leaving your browser open vulnerable.
Search for the path of your Chrome executable and then, on your cmd, try :
> "C:\PathTo\Chrome.exe" --allow-file-access-from-files
Source
EDIT :
As I see on your question, don't forget that Windows is a little bit similar to Unix, so when you type "chrome ...", cmd will search for Chrome in the PATH, but in general the Chrome folder isn't on the PATH. Also, you don't specify an extension for your executable... So if you move to Chrome's folder, this command will probably work too :
> .\chrome.exe --allow-file-access-from-files
You may want to try Web Server for Chrome, which serves web pages from a local folder using HTTP. It's simple to use and would avoid the flag, which, as someone mentioned above, might make your file system vulnerable.
As of this writing, in OS X, it will usually look like this
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --allow-file-access-from-files
If you are a freak like me, and put your apps in ~/Applications, then it will be
"/Users/yougohere/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --allow-file-access-from-files
If neither of those are working, then type chrome://version in your Chrome address bar, and it will tell you what "command line" invocation you should be using. Just add --allow-file-access-from-files to that.
Don't do this! You're opening your machine to attacks. Instead run a local server. It's as easy as opening a shell/terminal/commandline and typing
cd path/to/files
python -m SimpleHTTPServer
Then pointing your browser to
http://localhost:8000
If you find it's too slow consider this solution
If you are using a mac you can use the following terminal command:
open -a Google\ Chrome --args --allow-file-access-from-files
Quit (force quit) all instances of chrome. Otherwise the below command will not work.
open -a "Google Chrome" --args --allow-file-access-from-files
Executing this command in terminal will open Chrome regardless of where it is installed.
REM Kill all existing instance of chrome
taskkill /F /IM chrome.exe /T
REM directory path where chrome.exe is located
set chromeLocation="C:\Program Files (x86)\Google\Chrome\Application"
cd %chromeLocation%
cd c:
start chrome.exe --allow-file-access-from-files
save above lines as .bat file
Depending on the file which will be put into filesystem, as long as that file is not a malware, then that would be safe.
But don't worry to write/read file(s) to File System directory, cause you can tighten that directory security (include it's inheritance) by give a proper access right and security restriction. eg: read/write/modify.
By default, File System, Local Storage, and Storage directory are located on "\Users[Current User]\AppData\Local\Google\Chrome\User Data\Default" directory.
However you can customize it by using "--user-data-dir" flag.
And this is a sample:
"C:\Program Files (x86)\Google\Application\chrome.exe" --user-data-dir="C:\Chrome_Data\OO7" --allow-file-access-from-files
Hope this helps anyone.
Well there is quick to run a html which needs permission or blocked by CORS
Just simply open the folder using VSCODE and install an extension called "live server"
And then just click on the bottom which says go live, thats it.
Screenshot
On windows:
chrome --allow-file-access-from-files file:///C:/test%20-%203.html
On linux:
google-chrome --allow-file-access-from-files file:///C:/test%20-%203.html
I tried using the allow file access, but thought there was a better way. Found code that will pipe local file share files through http.
https://gist.github.com/andrii-riabchun/07f854939ce776f6e54ba6b64f43cc92
I added some edit suggestions. I used the revision code along with my edit suggestions. Also added a simple script to create index.html from ls ran on the webserver.
I use
google-chrome-beta --user-data-dir="/tmp/tmp-chrome-user-data-dir" --allow-file-access-from-files --disable-web-security file:///home/myuser/projects/myproject/myhtml.html
to disable has been blocked by CORS policy when I try to request('file://xxx')

What's the right way to enable the node debugger with mocha's --debug-brk switch?

I have some debugger statements in my module under test and want to run mocha with --debug-brk set and hit my breakpoint so that I can inspect the state of my module. Unfortunately, whenever I run mocha with this option, I end up with a blank cursor on the next line. I can enter text, but there's nothing that appears to be processing my commands (it certainly doesn't look like the node debugger):
$ mocha --debug-brk tests.js -R spec
debugger listening on port 5858
[BLANK CURSOR]
Am I doing something wrong with how I'm launching mocha?
UPDATE
As of mocha 7.0.0, --debug-brk has been removed in favor of --inspect-brk
Using a recent version of nodejs (>=v6.3.0) and mocha (>=3.1.0), you can use V8 inspector integration.
V8 Inspector integration allows attaching Chrome DevTools to Node.js
instances for debugging and profiling
Usage
--inspect activates V8 inspector integration, and --debug-brk adds a breakpoint at the beginning. Since nodejs v7.6.0 and mocha v3.3.0, you can use the --inspect-brk shorthand for --inspect --debug-brk
$ mocha --debug-brk --inspect
Debugger listening on port 9229.
Warning: This is an experimental feature and could change at any time.
To start debugging, open the following URL in Chrome:
chrome-devtools://devtools/remote/serve_file/#62cd277117e6f8ec53e31b1be58290a6f7ab42ef/inspector.html?experiments=true&v8only=true&ws=localhost:9229/node
With npm scripts
If you have a npm test script that uses mocha, you can pass the options from npm to your mocha script by using the end of option delimiter --:
$ npm test -- --inspect --debug-brk
Chrome tip
Instead of copy-pasting the url each time, go to chrome://inspect and click the appropriate link in the "Remote target" section.
To answer the original question, even though I also suggest you look into node-inspector: you can use the CLI debugger built into node through mocha with the debug option, instead of the --debug or --debug-brk flags. (Notice the lack of dashes.)
In your example, instead, it would be:
$ mocha debug tests.js -R spec
debugger listening on port 5858
connecting... ok
break in node_modules/mocha/bin/_mocha:7
5 */
6
7 var program = require('commander')
8 , sprintf = require('util').format
9 , path = require('path')
debug> [CURSOR]
Again, debug as above in bold, with no dashes. (=
Relevant: https://github.com/visionmedia/mocha/issues/247
I was able to get this to work using node-inspector. I run my test like you show in one shell:
mocha --debug-brk mocha/test.js
and then run node-inspector in a second shell:
node-inspector
Bringing up the URL that node-inspector spits out in a browser allows me to debug with the web inspector.
http://127.0.0.1:8080/debug?port=5858
If you have node-insector installed you can debug you Mocha tests without actually running node-inspector first. The easiest way is to
node-debug _mocha
That should start debugging the node tests in chrome (also works on Safari)
One reason I have seen that the tests do not work is sometimes you gave to try http://localhost:8080/debug?port=5858 or http://127.0.0.1:8080/debug?port=5858
run mocha with flag --inspect-brk and click 'open dedicated DevTools for node' in chrome from page chrome://inspect. In dedicated DevTools window add connection localhost:9229 to connect automatically.
Also add a debugger statement to the file you want debug.
(this is using latest versions of node and chrome as of October 2017)

Categories