Skip to content

add nonce support #162

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions src/NewWindow.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ class NewWindow extends React.PureComponent {
onUnload: null,
center: 'parent',
copyStyles: true,
closeOnUnmount: true
closeOnUnmount: true,
nonce: null
}

/**
Expand Down Expand Up @@ -134,7 +135,7 @@ class NewWindow extends React.PureComponent {

// If specified, copy styles from parent window's document.
if (this.props.copyStyles) {
setTimeout(() => copyStyles(document, this.window.document), 0)
setTimeout(() => copyStyles(document, this.window.document, this.props.nonce), 0)
}

if (typeof onOpen === 'function') {
Expand Down Expand Up @@ -206,7 +207,8 @@ NewWindow.propTypes = {
onOpen: PropTypes.func,
center: PropTypes.oneOf(['parent', 'screen']),
copyStyles: PropTypes.bool,
closeOnUnmount: PropTypes.bool
closeOnUnmount: PropTypes.bool,
nonce: PropTypes.string
}

/**
Expand All @@ -221,7 +223,7 @@ NewWindow.propTypes = {
* @private
*/

function copyStyles(source, target) {
function copyStyles(source, target, nonce) {
// Store style tags, avoid reflow in the loop
const headFrag = target.createDocumentFragment()

Expand Down Expand Up @@ -275,13 +277,15 @@ function copyStyles(source, target) {

const newStyleEl = target.createElement('style')
newStyleEl.textContent = ruleText.join('\n')
if (nonce) newStyleEl.setAttribute('nonce', nonce);
headFrag.appendChild(newStyleEl)
} else if (styleSheet.href) {
// for <link> elements loading CSS from a URL
const newLinkEl = target.createElement('link')

newLinkEl.rel = 'stylesheet'
newLinkEl.href = styleSheet.href
if (nonce) newLinkEl.setAttribute('nonce', nonce);
headFrag.appendChild(newLinkEl)
}
})
Expand Down
7 changes: 6 additions & 1 deletion types/NewWindow.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,16 @@ declare module 'react-new-window' {
* If specified, copy styles from parent window's document.
*/
copyStyles?: boolean

/**
* If specified, close the new window on unmount.
*/
closeOnUnmount?: boolean

/**
* If specified, adds nonce to style elements.
*/
nonce?: string | null
}

export default class NewWindow extends React.PureComponent<INewWindowProps> {
Expand Down