Add custom CSP

    @@ -1,16 +1,30 @@ /* - * @title Apply custom CSP - * @description add/modify CSP meta tag & reload + * @title Add custom CSP + * @description お好みの Content-Security-Policy を追加して、制限を厳しくしてみよう * @include http://* * @include https://* * @license MIT License * @javascript_url */ -(function(){ - let csp = document.querySelector('meta[http-equiv^="Content-Security-Policy"]') || document.createElement("meta"); +(function() { + // 後から追加変更することで厳しくはできても、**緩くはできない** + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy#Multiple_content_security_policies + // なので、既存のmetaタグを再利用する意味はない + let csp = doc.createElement("meta"); csp.httpEquiv = "Content-Security-Policy"; csp.content = prompt("Enter policy:", "default-src 'self'") || ''; - document.querySelector('head').appendChild(csp); - document.documentElement.innerHTML = document.documentElement.innerHTML; -})(); + doc.querySelector('head').appendChild(csp); + + // 設定したポリシーを反映するために再読み込み + let xhr = new XMLHttpRequest(); + xhr.open("GET", location.href); + xhr.responseType = "document"; + xhr.onload = function() { + let doc = xhr.response; + // documentElementを入れ替えるとmetaタグは消えるが、 + // ポリシーはリセットされないので再設定する甲斐はあまりない + document.replaceChild(doc.documentElement, document.documentElement); + }; + xhr.send(); +})();
  • /*
     * @title Add custom CSP
     * @description お好みの Content-Security-Policy を追加して、制限を厳しくしてみよう
     * @include http://*
     * @include https://*
     * @license MIT License
     * @javascript_url
     */
    
    (function() {
      // 後から追加変更することで厳しくはできても、**緩くはできない**
      // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy#Multiple_content_security_policies
      // なので、既存のmetaタグを再利用する意味はない
      let csp = doc.createElement("meta");
      csp.httpEquiv = "Content-Security-Policy";
      csp.content = prompt("Enter policy:", "default-src 'self'") || '';
      doc.querySelector('head').appendChild(csp);
    
      // 設定したポリシーを反映するために再読み込み
      let xhr = new XMLHttpRequest();
      xhr.open("GET", location.href);
      xhr.responseType = "document";
      xhr.onload = function() {
        let doc = xhr.response;
        // documentElementを入れ替えるとmetaタグは消えるが、
        // ポリシーはリセットされないので再設定する甲斐はあまりない
        document.replaceChild(doc.documentElement, document.documentElement);
      };
      xhr.send();
    })();
  • Permalink
    このページへの個別リンクです。
    RAW
    書かれたコードへの直接のリンクです。
    Packed
    文字列が圧縮された書かれたコードへのリンクです。
    Userscript
    Greasemonkey 等で利用する場合の .user.js へのリンクです。
    Loader
    @require やソースコードが長い場合に多段ロードする Loader コミのコードへのリンクです。
    Metadata
    コード中にコメントで @xxx と書かれたメタデータの JSON です。

History

  1. 2017/03/11 19:10:06 - 2017-03-11
  2. 2017/03/09 20:41:43 - 2017-03-09
  3. 2017/03/09 20:32:05 - 2017-03-09
  4. 2017/03/06 00:42:06 - 2017-03-06