My company switched to B2C and now the login is performed with a redirection from another website. For this reason my login tests that used to work now are giving me a cross origin error.
Already tried adding chromeWebSecurity: false to cypress.json and it makes no difference.
Also tried to add this to index.js :
on('before:browser:launch', (browser = {}, launchOptions) => {
// `args` is an array of all the arguments that will
// be passed to browsers when it launches
console.log(launchOptions.args) // print all current args
if (browser.family === 'chromium' && browser.name !== 'electron') {
// auto open devtools
launchOptions.args.push('--auto-open-devtools-for-tabs')
// whatever you return here becomes the launchOptions
return launchOptions
}
if (browser.family === 'firefox') {
// auto open devtools
launchOptions.args.push('-devtools')
return launchOptions
}
})
Didnt make any difference either.
From what I read, many people are having this issue since 2018 and Cypress didnt seem to have solved it yet. Kind of make me nervous because I already have A LOT of tests written for cypress, so migrating would be harsh.
Do you guys know any workaround?
Here's the full error:
CypressError
Cypress detected a cross origin error happened on page load:
Blocked a frame with origin "my company's address" from accessing a cross-origin frame.
Before the page load, you were bound to the origin policy:
my company's address
A cross origin error happens when your application navigates to a new URL which does not match the origin policy above.
A new URL does not match the origin policy if the 'protocol', 'port' (if specified), and/or 'host' (unless of the same superdomain) are different.
Cypress does not allow you to navigate to a different origin URL within a single test.
You may need to restructure some of your test code to avoid this problem.
Alternatively you can also disable Chrome Web Security in Chromium-based browsers which will turn off this restriction by setting { chromeWebSecurity: false } in cypress.json.Learn more
Related
I have an Electron app that uses a custom app:// protocol to serve files. It seems that Chrome/Electron considers all files returned from that protocol to be from the same origin. This means that app pages have the same zoom level, which isn't what I want.
How does Electron determine the origin in this case (a pointer to the code would be helpful) and is there any way to convince it that some URLs are from different origins, short of registering another protocol like app2://?
I found some documentation in the Chromium source code:
// Zoom can be defined at three levels: default zoom, zoom for host, and zoom
// for host with specific scheme. Setting any of the levels leaves settings
// for other settings intact. Getting the zoom level starts at the most
// specific setting and progresses to the less specific: first the zoom for the
// host and scheme pair is checked, secondly the zoom for the host only and
// lastly default zoom.
And in zoom_controller.cc it seems like it just uses the scheme/host from the URL:
GURL url = content::HostZoomMap::GetURLFromEntry(entry);
std::string host = net::GetHostOrSpecFromURL(url);
if (zoom_map->HasZoomLevel(url.scheme(), host)) {
// If there are other tabs with the same origin, then set this tab's
// zoom level to match theirs. The temporary zoom level will be
// cleared below, but this call will make sure this tab re-draws at
// the correct zoom level.
double origin_zoom_level =
zoom_map->GetZoomLevelForHostAndScheme(url.scheme(), host);
And
std::string GetHostOrSpecFromURL(const GURL& url) {
return url.has_host() ? TrimEndingDot(url.host_piece()) : url.spec();
}
url.spec() actually returns the entire URL, which suggests to me that if I browse file:// URLs they'll get separate zoom levels. I verified this experimentally and it does seem to be the case.
In any case I figured out what was happening in my case - I was running in development mode which uses the WebPack dev server. In that case all files are served from localhost so they always get the same zoom.
However in production using the app:// protocol my code was setting the host to . so URLs were like app://./index.html. The host was actually ignored by the custom protocol handler, so to give windows separate origins you can just make up a fake hostname for them, like app://main/index.html or app://help/help.html. Seems to work perfectly.
I'm testing out some audio worklet code by loading an example module from Github via AudioWorklet.addModule(githubUrl). However when I look at the network tab in developer settings I don't see a network request to Github. I know that it is making the request because it was giving a CORS error before I switched to using raw.githubusercontent address (now it is giving Uncaught (in promise) DOMException: The user aborted a request). I want to be able to inspect what the network call is returning so I can help diagnose the problem.
There seems to be a bug in Chrome which prevents the network request from being shown in the dev tools. I think it would be a good idea to file a bug for that.
For now you could just use Firefox. It shows the network request in the dev tools.
If you want to keep using Chrome you can proxy your request with fetch() to make it appear in the devtools.
Instead of calling addModule() directly ...
context.audioWorklet.addModule(url)
... you could fetch the source first and then wrap it into an object URL.
fetch(url)
.then((response) => response.text())
.then((text) => {
const blob = new Blob([text], { type: 'application/javascript; charset=utf-8' });
const objectUrl = URL.createObjectURL(blob);
return context.audioWorklet.addModule(objectUrl)
.finally(() => URL.revokeObjectURL(objectUrl));
})
I'm new to cypress and have ran into an issue. I have my base URL set to the domain I want to test, the issue is when I want to test the ability to login on my base url site I need to verify the user on another site, once I click apply on site number 2 the page on my base url reloads and I would then be able to test the rest of the site.
When I try to visit site 2 from my test I get an error
cy.visit() failed because you are attempting to visit a URL that is of
a different origin.
The new URL is considered a different origin because the following
parts of the URL are different:
superdomain
You may only cy.visit() same-origin URLs within a single test.
I read this https://docs.cypress.io/guides/guides/web-security.html#Set-chromeWebSecurity-to-false I've tried setting "chromeWebSecurity": false in cypress.json but I still get the same issue (I'm running in chrome)
Is there something I am missing?
As a temporary but solid work around, I was able to find this script in one of the Cypress Git issue threads (I don't remember where I found it so I can't link back to it)
Add the below to your cypress commands file
Cypress.Commands.add('forceVisit', url => {
cy.window().then(win => {
return win.open(url, '_self');
});
});
and in your tests you can call
cy.forceVisit("www.google.com")
From version 9.6.0 of cypress, you can use cy.origin.
If you want to use it, you must first set the "experimentalSessionAndOrigin" record to true.
{
"experimentalSessionAndOrigin": true
}
And here's how to use it.
cy.origin('www.example.com', () => {
cy.visit('/')
})
cy.origin change the baseurl, so you can link to another external link via cy.visit('/').
You can stub the redirect from login site to base site, and assert the URL that was called.
Based on Cypress tips and tricks here is a custom command to do the stubbing.
The login page may be using one of several methods to redirect, so besides the replace(<new-url>) stub given in the tip I've added href = <new-url> and assign(<new-url>).
Stubbing command
Cypress.Commands.add('stubRedirect', () => {
cy.once('window:before:load', (win) => {
win.__location = { // set up the stub
replace: cy.stub().as('replace'),
assign: cy.stub().as('assign'),
href: null,
}
cy.stub(win.__location, 'href').set(cy.stub().as('href'))
})
cy.intercept('GET', '*.html', (req) => { // catch the page as it loads
req.continue(res => {
res.body = res.body
.replaceAll('window.location.replace', 'window.__location.replace')
.replaceAll('window.location.assign', 'window.__location.assign')
.replaceAll('window.location.href', 'window.__location.href')
})
}).as('index')
})
Test
it('checks that login page redirects to baseUrl', () => {
cy.stubRedirect()
cy.visit(<url-for-verifying-user>)
cy.wait('#index') // waiting for the window load
cy.('button').contains('Apply').click() // trigger the redirect
const alias = '#replace' // or '#assign' or '#href'
// depending on the method used to redirect
// if you don't know which, try each one
cy.get(alias)
.should('have.been.calledOnceWith', <base-url-expected-in-redirect>)
})
You can't!
But, maybe it will be possible soon. See Cypress ticket #944.
Meanwhile you can refer to my lighthearted comment in the same thread where I describe how I cope with the issue while Cypress devs are working on multi-domain support:
For everyone following this, I feel your pain! #944 (comment) really gives hope, so while we're patiently waiting, here's a workaround that I'm using to write multi-domain e2e cypress tests today. Yes, it is horrible, but I hope you will forgive me my sins. Here are the four easy steps:
Given that you can only have one cy.visit() per it, write multiple its.
Yes, your tests now depend on each other. Add cypress-fail-fast to make sure you don't even attempt to run other tests if something failed (your whole describe is a single test now, and it makes sense in this sick alternate reality).
It is very likely that you will need to pass data between your its. Remember, we're already on this crazy “wrong” path, so nothing can stop us naughty people. Just use cy.writeFile() to save your state (whatever you might need), and use cy.readFile() to restore it at the beginning of your next it.
Sue me.
All I care about at this point is that my system has tests. If cypress adds proper support for multiple domains, fantastic! I'll refactor my tests then. Until that happens, I'd have to live with horrible non-retriable tests. Better than not having proper e2e tests, right? Right?
You could set the window.location.href manually which triggers a page load, this works for me:
const url = 'http://localhost:8000';
cy.visit(url);
// second "visit"
cy.window().then(win => win.location.href = url);
You will also need to add "chromeWebSecurity": false to your cypress.json configuration.
Note: setting the window to navigate won't tell cypress to wait for the page load, you need to wait for the page to load yourself, or use timeout on get.
I'm having a problem with push notifications on Chrome. On certain pcs in my network, websites normally requesting permissions to post push notifications, don't request them. That functionality works on some browsers in my network, but doesn't on others. Chrome version is 68.0.3440.106 on all the machines.
To investigate the case, I run a simple script in the console, that should trigger the browser request:
Notification.requestPermission().then(function(result) {
if (result === 'denied') {
console.log('denied');
return;
}
if (result === 'default') {
console.log('default');
return;
}
console.log(result);
return;
});
On the machines where push is working as expected, this promise resolves, whereas on the "faulty" ones, it doesn't resolve. I don't have my browser configured to either allow or deny the notifications (I've never clicked the "allow" or "deny" on the request, as it has never appeared). I don't know where to go from here, here's what I've tried so far:
I don't have the browser notification behaviour set to either allow or deny.
Chrome://flags shows "default" for all entries concerning push notifications.
Console doesn't print any errors/warnings
running chrome with --enable-logging --v=1 doesn't show anything suspicious when running the script. Here's an excerpt:
[7772:21772:0828/101500.364:VERBOSE1:thread_state.cc(1024)] [state:00007FFB173B67A0] PostSweep: collection_rate: 0.00067%
[7772:21772:0828/101500.421:VERBOSE1:thread_state.cc(1024)] [state:00007FFB173B67A0] PostSweep: collection_rate: 0%
[7772:21772:0828/101500.422:VERBOSE1:thread_state.cc(1430)] [state:00007FFB173B67A0] CollectGarbage: time: 15ms stack: HeapPointersOnStack marking: AtomicMarking sweeping: EagerSweeping reason: ForcedGC
[7772:21772:0828/101500.427:VERBOSE1:thread_state.cc(1430)] [state:00007FFB173B67A0] CollectGarbage: time: 4.9ms stack: NoHeapPointersOnStack marking: AtomicMarking sweeping: LazySweeping reason: PreciseGC
I'd really appreciate it if someone could tell me what else to check, I'm really lost with this one. Thanks in advance!
Edit: Apparently this is some weird screen offset issue. The request shows just fine, when I have two instances of chrome running. However, when I have the request showing in one window, snapping it back to the other instance makes the request disappear. It reappears after resising the window to anything but fullscreen, or undocking the tab. Has nobody encountered this problem? This occurs among multiple machines in my workplace
I have a chrome extension which monitors the browser in a special way, sending some data to a web-server. In the current configuration this is the localhost. So the content script contains a code like this:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(data)...
xhr.open('GET', url, true);
xhr.send();
where url parameter is 'http://localhost/ctrl?params' (or http://127.0.0.1/ctrl?params - it doesn't matter).
Manifest-file contains all necessary permissions for cross-site requests.
The extension works fine on most sites, but on one site I get the error:
XMLHttpRequest cannot load http://localhost/ctrl?params. Origin http://www.thissite.com is not allowed by Access-Control-Allow-Origin.
I've tried several permissions which are proposed here (*://*/*, http://*/*, and <all_urls>), but no one helped to solve the problem.
So, the question is what can be wrong with this specific site (apparently there may be another sites with similar misbehaviour, and I'd like to know the nature of this), and how to fix the error?
(tl;dr: see two possible workarounds at the end of the answer)
This is the series of events that happens, which leads to the behavior that you see:
http://www.wix.com/ begins to load
It has a <script> tag that asynchronously loads the Facebook Connect script:
(function() {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
Once the HTML (but not resources, including the Facebook Connect script) of the wix.com page loads, the DOMContentLoaded event fires. Since your content script uses "run_at" : "document_end", it gets injected and run at this time.
Your content script runs the following code (as best as I can tell, it wants to do the bulk of its work after the load event fires):
window.onload = function() {
// code that eventually does the cross-origin XMLHttpRequest
};
The Facebook Connect script loads, and it has its own load event handler, which it adds with this snippet:
(function() {
var oldonload=window.onload;
window.onload=function(){
// Run new onload code
if(oldonload) {
if(typeof oldonload=='string') {
eval(oldonload);
} else {
oldonload();
}
}
};
})();
(this is the first key part) Since your script set the onload property, oldonload is your script's load handler.
Eventually, all resources are loaded, and the load event handler fires.
Facebook Connect's load handler is run, which run its own code, and then invokes oldonload. (this is the second key part) Since the page is invoking your load handler, it's not running it in your script's isolated world, but in the page's "main world". Only the script's isolated world has cross-origin XMLHttpRequest access, so the request fails.
To see a simplified test case of this, see this page (which mimics http://www.wix.com), which loads this script (which mimics Facebook Connect). I've also put up simplified versions of the content script and extension manifest.
The fact that your load handler ends up running in the "main world" is most likely a manifestation of Chrome bug 87520 (the bug has security implications, so you might not be able to see it).
There are two ways to work around this:
Instead of using "run_at" : "document_end" and a load event handler, you can use the default running time (document_idle, after the document loads) and just have your code run inline.
Instead of adding your load event handler by setting the window.onload property, use window.addEventListener('load', func). That way your event handler will not be visible to the Facebook Connect, so it'll get run in the content script's isolated world.
The access control origin issue you're seeing is likely manifest in the headers for the response (out of your control), rather than the request (under your control).
Access-Control-Allow-Origin is a policy for CORS, set in the header. Using PHP, for example, you use a set of headers like the following to enable CORS:
header('Access-Control-Allow-Origin: http://blah.com');
header('Access-Control-Allow-Credentials: true' );
header('Access-Control-Allow-Headers: Content-Type, Content-Disposition, attachment');
If sounds like that if the server is setting a specific origin in this header, then your Chrome extension is following the directive to allow cross-domain (POST?) requests from only that domain.