使其能够在不使用 CSP style-src 'unsafe-inline' (即不在组件中加载内联 CSS) 的情况下使用

作者: rugk创建于 2025年3月7日更新于 2025年10月14日

STR

I use this content security policy (CSP) (in my case in a browser extension, but it can likewise be done on any website):

csp
default-src 'self'; img-src data:; style-src 'self' https://unpkg.com; script-src 'self' https://unpkg.com

The setup is quite minimal and basically boils down to your Readme browser example with some (you can ignore/remove the settings, they do not matter):

javascript
export function init(settings) {
    const initProperties = Object.assign(settings, hardcodedSettings);
    initProperties.emojiButtonSize = initProperties.emojiSize + 12;

    console.debug("Using these emoji-mart settings:", initProperties);

    const emojiPicker = new EmojiMart.Picker({ ...initProperties, data: async () => {
        const response = await fetch(browser.runtime.getURL(`/node_modules/@emoji-mart/data/sets/${initProperties.emojiVersion}/${initProperties.set}.json`));

        return await response.json();
    }});

    // NOTE: Typing is not updated yet, so cannot be used here: https://GitHub.com/missive/emoji-mart/issues/576
    // @ts-ignore
    document.body.appendChild(emojiPicker);
    console.info("Created EmojiPicker component:", emojiPicker);
}
### What happens
Now if you do this, you get a CSP error:
> Content-Security-Policy: Die Einstellungen der Seite haben die Anwendung eines Inline-Styles (style-src-elem) blockiert, da er gegen folgende Direktive verstößt: "style-src 'self' https://unpkg.com/"
Roughly translated as:
> Content security policy: The page settings have blocked the use of an inline style (style-src-elem) because it violates the following directive: 'style-src "self" https://unpkg.com/'
*And* for obvious reasons the CSS/style is not applied, so it looks horribly broken:
<details>

![Image](https://GitHub.com/user-attachments/assets/e58236cc-03d0-48fc-a541-8be19c431433)

</details>
## Workaround
Adding [`'unsafe-inline'`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy#unsafe-inline) to [`style-src`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/style-src) fixes it aka:
```csp
default-src 'self'; img-src data:; style-src 'self' 'unsafe-inline' https://unpkg.com; script-src 'self' https://unpkg.com

What should happen

Anyway, IMHO, this is no real solution. Instead, it should best work with the strictest CSP possible. For security reasons… because otherwise it prevents such a strict CSP everywhere on the site (unless some clever tricks may be used, but well). 'unsafe-inline' is indeed unsafe and should be avoided if possible. And all in all, the aim of CSP is to prevent XSS attacks. When a component forces you to weaken the CSP, that is not good, IMHO. Now, I don't know whether this can be solved or if this is some thing …

内容来源: missive/emoji-mart