js iframe内のCSSを変更したい(クロスドメイン)

ドメインの異なるページをiframeで読み込んでCSSを変更したい

作成日:2023-02-06, 更新日:2023-02-06

クロスドメイン+iframeのCSS変更

クロスドメインとは言え、自分が管理しているサイトってのが前提

▼やること

  • iframeを設置する側の処理
  • iframeで読み込まれる側の処理

iframeを設置する側の処理

<iframe id="id_iframe" href="~読み込むURL~"></iframe>
<script>
  let iframeOBJ = document.getElementById('id_iframe').contentWindow;
  iframeOBJ.postMessage("~任意の文字列~", '~読み込むURL~');
</script>

iframeで読み込まれる側の処理

<script>
  window.addEventListener('message', function(event){
    if("CSS書換え" == event.data ) {
      // ~ 好きな処理 ~
      // $(XXX).css('xxx', 'xxx');
      // $(XXX).addClass('xxx');
      // $('head').append('<link type="text/css" rel="stylesheet" href="http://example.com/hoge.css">');
    }
  });
</script>

同一ドメイン+iframeのCSS変更

<iframe id="id_iframe" href="~読み込むURL~"></iframe>
<script>
  $('#id_iframe').on("load",function(){
    $('#id_iframe').contents().find(xxx).css('xxx', 'xxx');
  });
</script>