> ## Documentation Index
> Fetch the complete documentation index at: https://moengage.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# コンテンツセキュリティポリシー（CSP）Nonce のサポート

> 厳格なコンテンツセキュリティポリシーに準拠するために、MoEngage Web SDK の CSP Nonce サポートを設定します。

## 概要

[コンテンツセキュリティポリシー（CSP）](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CSP)は、[クロスサイトスクリプティング（XSS）](https://developer.mozilla.org/en-US/docs/Glossary/Cross-site_scripting)を含む特定の種類の攻撃を検出して軽減するのに役立つ重要なセキュリティレイヤーです。厳格な CSP ディレクティブは、On-Site Messaging（OSM）、Web Personalization（WebP）、Cards などの MoEngage のアセットをブロックすることがよくあります。これは、これらのコンポーネントが従来、インラインイベントハンドラーや動的なスクリプト実行に依存しているためです。

サイトのセキュリティを損なうことなくシームレスな統合を実現するために、MoEngage Web SDK は暗号化 Nonce をサポートしています。初期化時に Nonce が指定されると、SDK は次の処理を行います。

1. **属性の挿入**: 動的に作成されるすべての `<script>` タグに Nonce を自動的に付与します。
2. **ハンドラーのリファクタリング**: SDK によって作成されたアセットのインラインイベントハンドラー（`onclick` など）を、CSP に準拠した内部スクリプトにリファクタリングします。

## CSP ヘッダーの設定

> [!NOTE]
>
> Nonce を設定する前に、CSP ヘッダー（script-src、connect-src、img-src など）で MoEngage のドメインがホワイトリストに登録されていることを確認してください。詳細については、[Web SDK Integration](https://www.moengage.com/docs/developer-guide/web-sdk/web-sdk-integration/basic-integration/web-sdk-integration#whitelisting-urls) を参照してください。

この機能を実装するには、セッション用に生成された特定の Nonce を信頼するように、サーバー側の CSP ヘッダーを設定する必要があります。

```javascript CSP Header lines wrap theme={null}
Content-Security-Policy: script-src 'self' 'nonce-GENERATED_NONCE_VALUE' https://cdn.moengage.com/ https://app-cdn.moengage.com/;
```

> [!WARNING]
>
> 効果的なセキュリティを確保するため、Nonce はページの読み込みごとに生成される、暗号学的に強力な一意の値である必要があります。本番環境では、ハードコードされた Nonce を決して使用しないでください。

## 初期化と設定

CSP のサポートを有効にするには、生成された Nonce を Web SDK 統合スクリプトと SDK 初期化設定の両方に渡す必要があります。

### 1. Web SDK の統合

SDK が後続の DOM 操作やコンポーネントのレンダリングに Nonce を適用できるように、初期化フェーズで Nonce を渡します。

```javascript JavaScript wrap theme={null}
<script type="text/javascript" nonce="GENERATED_NONCE_VALUE">
    var moeDataCenter = "{DC}"; // Replace "DC" with the actual Data center value from the above table
    var moeAppID = "{WorkspaceID}"; // Replace "WorkspaceID" available in the settings page of MoEngage Dashboard.
    var sdkVersion = "2"; // Replace this value with the version of Web SDK that you intend to use. It is recommended to use the format x (major)
    !function(e,n,i,t,a,r,o,d){if(!moeDataCenter||!moeDataCenter.match(/^dc_[0-9]+$/gm))return console.error("Data center has not been passed correctly. Please follow the SDK installation instruction carefully.");var s=e[a]=e[a]||[];if(s.invoked=0,s.initialised>0||s.invoked>0)return console.error("MoEngage Web SDK initialised multiple times. Please integrate the Web SDK only once!"),!1;e.moengage_object=a;var l={},g=function n(i){return function(){for(var n=arguments.length,t=Array(n),a=0;a<n;a++)t[a]=arguments[a];(e.moengage_q=e.moengage_q||[]).push({f:i,a:t})}},u=["track_event","add_user_attribute","add_first_name","add_last_name","add_email","add_mobile","add_user_name","add_gender","add_birthday","destroy_session","add_unique_user_id","update_unique_user_id","moe_events","call_web_push","track","location_type_attribute","setLogLevel","setDebugLevel","handle_page_change","identifyUser","getUserIdentities","trackEvent","trackPageView","track_page_view","setUserAttribute","setFirstName","setLastName","setEmailId","setMobileNumber","setUserName","setGender","setBirthDate","logoutUser","callWebPush","handlePageChange","enableSdk","disableSdk","enableDataTracking","disableDataTracking"],m={onsite:["getData","registerCallback","getSelfHandledOSM"]};for(var c in u)l[u[c]]=g(u[c]);for(var v in m)for(var f in m[v])null==l[v]&&(l[v]={}),l[v][m[v][f]]=g(v+"."+m[v][f]);r=n.createElement(i),o=n.getElementsByTagName("head")[0],r.async=1,r.src=t,o.appendChild(r),e.moe=e.moe||function(){return(s.invoked=s.invoked+1,s.invoked>1)?(console.error("MoEngage Web SDK initialised multiple times. Please integrate the Web SDK only once!"),!1):(d=arguments.length<=0?void 0:arguments[0],l)},r.addEventListener("load",function(){if(d)return e[a]=e.moe(d),e[a].initialised=e[a].initialised+1||1,!0}),r.addEventListener("error",function(){return console.error("Moengage Web SDK loading failed."),!1})}(window,document,"script","https://cdn.moengage.com/release/"+moeDataCenter+"/versions/"+sdkVersion+"/moe_webSdk.min.latest.js","Moengage");
    
    Moengage = moe({
      appId: moeAppID,
      env: 'LIVE',
      logLevel: 0,
      contentSecurityNonce: 'GENERATED_NONCE_VALUE',
    });
</script>
```

### 2. Web Personalization（WebP）

Web Personalization を利用している場合は、DOM にデプロイされたパーソナライズコンテンツがブラウザによってブロックされないように、WebP スクリプトの URL に Nonce を付加する必要があります。

> [!NOTE]
>
> 以下のスクリプトを、実際のデータセンターの値と app\_id で更新してください。詳細については、[Web Personalization](https://www.moengage.com/docs/developer-guide/personalize-sdk/sdk-integration/web-personalization-v2) を参照してください。

```html WebP Script wrap theme={null}
<link rel="preconnect" href="https://cdn.moengage.com/" crossorigin />
<link rel="dns-prefetch" href="https://cdn.moengage.com/" />
<link rel="preconnect" href="https://sdk-01.moengage.com/" crossorigin />
<link rel="dns-prefetch" href="https://sdk-01.moengage.com/" />
<script src="https://cdn.moengage.com/release/dc_1/versions/2/moe_webSdk_webp.min.latest.js?app_id=YOUR_WORKSPACE_ID&contentSecurityNonce=GENERATED_NONCE_VALUE"></script>
```

## フレームワークとプラットフォームの互換性

この機能は、次のフレームワークで利用できます。

* NPM
* GTM
* Flutter Web

## 検証

次のようにコンソールを分析することで、実装が成功したかどうかを検証できます。

**コンソールの分析**: Nonce が欠落しているか一致しない場合、ブラウザは `Refused to execute inline event handler because it violates the following Content Security Policy directive…”` という違反をログに記録します。

## よくある質問

**Nonce が指定されていない場合はどうなりますか？**

コンテンツセキュリティポリシー（CSP）に script-src が含まれているものの 'unsafe-inline' が含まれていない場合、Nonce を指定しないと、On-site Messaging や Cards などの SDK によって生成される機能が CSP によってブロックされます。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.