[jQuery] iframe 내 element의 스타일 수정하기

2021. 5. 26. 22:58각종 코딩 관련

안녕하세요.

 

오늘은 개인 프로젝트로 크롬 익스텐션을 만들면서, 웹사이트(content 레이어) 상의 iframe 내의 element 스타일을 수정할 일이 있어서 이것저것 알아보았습니다. jQuery를 이용하면 쉽게 해결할 수 있습니다.

 

하지만 우선 이를 위해서는, iframe을 로드하는 도메인과 iframe 안에 보여질 콘텐츠를 로드하는 도메인이 같아야 합니다.

예를 들어서 제 블로그 글에서 네이버 화면을 iframe으로 가져오는 경우에는 해당 iframe 내부에 접근할 수 없다는 뜻입니다.

 

제가 사용한 코드는 아래와 같습니다.

 

$("#iframe_id").on("load", function() {
    let head = $("#iframe_id").contents().find("head");
    let css = '< style>/* 여기에 css 코드를 쓰세요 */< /style>';
    $(head).append(css);
});

 

저는 스타일 두 개만 수정하면 되었기 때문에 style 태그를 iframe 내 document의 head 안에 넣어주었습니다.

비슷한 원리로 아래처럼 별도 css 파일도 주입해줄 수 있습니다.

 

// ...
$(head).append($("< link/>", {
    rel: "stylesheet",
    href: url,
    type: "text/css"
}));

 

 

이와 관련해 아래 문서를 보면 많은 도움이 될 겁니다.

https://stackoverflow.com/questions/217776/how-to-apply-css-to-iframe

 

How to apply CSS to iframe?

I have a simple page that has some iframe sections (to display RSS links). How can I apply the same CSS format from the main page to the page displayed in the iframe?

stackoverflow.com