Skip to content

Commit caaafd9

Browse files
authored
fix(browser): allow iframe to load even if there is a custom CSP header (#5841)
1 parent c79b3f1 commit caaafd9

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

packages/browser/src/node/index.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,13 @@ export default (project: WorkspaceProject, base = '/'): Plugin[] => {
7474
__VITEST_TYPE__: url.pathname === base ? '"orchestrator"' : '"tester"',
7575
})
7676

77+
// remove custom iframe related headers to allow the iframe to load
78+
res.removeHeader('X-Frame-Options')
79+
7780
if (url.pathname === base) {
81+
// disable CSP for the orchestrator as we are the ones controlling it
82+
res.removeHeader('Content-Security-Policy')
83+
7884
if (!indexScripts)
7985
indexScripts = await formatScripts(project.config.browser.indexScripts, server)
8086

@@ -105,6 +111,13 @@ export default (project: WorkspaceProject, base = '/'): Plugin[] => {
105111
return
106112
}
107113

114+
const csp = res.getHeader('Content-Security-Policy')
115+
if (typeof csp === 'string') {
116+
// add frame-ancestors to allow the iframe to be loaded by Vitest,
117+
// but keep the rest of the CSP
118+
res.setHeader('Content-Security-Policy', csp.replace(/frame-ancestors [^;]+/, 'frame-ancestors *'))
119+
}
120+
108121
const decodedTestFile = decodeURIComponent(url.pathname.slice(testerPrefix.length))
109122
const testFiles = await project.globTestFiles()
110123
// if decoded test file is "__vitest_all__" or not in the list of known files, run all tests

test/browser/vitest.config.mts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@ export default defineConfig({
1818
server: {
1919
headers: {
2020
'x-custom': 'hello',
21+
// Vitest iframe should still be loaded
22+
'X-Frame-Options': 'DENY',
23+
'content-security-policy': 'frame-src https://example.com; frame-ancestors https://example.com',
2124
},
2225
},
2326
optimizeDeps: {

0 commit comments

Comments
 (0)