Programing

iframe에 CSS를 적용하는 방법은 무엇입니까?

lottogame 2020. 9. 28. 07:56
반응형

iframe에 CSS를 적용하는 방법은 무엇입니까?


RSS 링크를 표시하기 위해 iframe 섹션이있는 간단한 페이지가 있습니다. 메인 페이지의 동일한 CSS 형식을 iframe에 표시된 페이지에 적용하려면 어떻게해야합니까?


편집 : 적절한 CORS 헤더 가 설정되어 있지 않으면 도메인 간 작동하지 않습니다 .

여기에는 iframe 블록의 스타일과 iframe에 포함 된 페이지의 스타일의 두 가지가 있습니다. 일반적인 방법으로 iframe 블록의 스타일을 설정할 수 있습니다.

<iframe name="iframe1" id="iframe1" src="empty.htm" 
        frameborder="0" border="0" cellspacing="0"
        style="border-style: none;width: 100%; height: 120px;"></iframe>

iframe에 삽입 된 페이지의 스타일은 하위 페이지에 포함하여 설정해야합니다.

<link type="text/css" rel="Stylesheet" href="Style/simple.css" />

또는 Javascript를 사용하여 상위 페이지에서로드 할 수 있습니다.

var cssLink = document.createElement("link");
cssLink.href = "style.css"; 
cssLink.rel = "stylesheet"; 
cssLink.type = "text/css"; 
frames['iframe1'].document.head.appendChild(cssLink);

Google 캘린더 에서이 문제를 만났습니다 . 더 어두운 배경에서 스타일을 지정하고 글꼴을 변경하고 싶었습니다.

다행히 임베드 코드의 URL은 직접 액세스에 제한이 없었기 때문에 PHP 기능을 사용 file_get_contents하면 페이지에서 전체 콘텐츠를 가져올 수 있습니다. Google URL을 호출하는 대신 서버에있는 php 파일을 호출 할 수 있습니다. google.php, 수정 된 원본 콘텐츠가 포함됩니다.

$content = file_get_contents('https://www.google.com/calendar/embed?src=%23contacts%40group.v.calendar.google.com&ctz=America/Montreal');

스타일 시트에 경로 추가 :

$content = str_replace('</head>','<link rel="stylesheet" href="http://www.yourwebsiteurl.com/google.css" /></head>', $content);

(이렇게하면 스타일 시트가 head끝 태그 바로 전에 마지막에 배치됩니다 .)

css 및 js가 상대적으로 호출되는 경우 기본 URL을 원래 URL 형식으로 지정합니다.

$content = str_replace('</title>','</title><base href="https://www.google.com/calendar/" />', $content);

최종 google.php파일은 다음과 같아야합니다.

<?php
$content = file_get_contents('https://www.google.com/calendar/embed?src=%23contacts%40group.v.calendar.google.com&ctz=America/Montreal');
$content = str_replace('</title>','</title><base href="https://www.google.com/calendar/" />', $content);
$content = str_replace('</head>','<link rel="stylesheet" href="http://www.yourwebsiteurl.com/google.css" /></head>', $content);
echo $content;

그런 다음 iframe소스 코드를 다음과 같이 변경합니다 .

<iframe src="http://www.yourwebsiteurl.com/google.php" style="border: 0" width="800" height="600" frameborder="0" scrolling="no"></iframe>

행운을 빕니다!


iframe의 콘텐츠가 완전히 제어되지 않거나 다른 스타일의 다른 페이지에서 콘텐츠에 액세스하려는 경우 JavaScript를 사용하여 조작 해 볼 수 있습니다.

var frm = frames['frame'].document;
var otherhead = frm.getElementsByTagName("head")[0];
var link = frm.createElement("link");
link.setAttribute("rel", "stylesheet");
link.setAttribute("type", "text/css");
link.setAttribute("href", "style.css");
otherhead.appendChild(link);

사용하는 브라우저에 따라 동일한 도메인에서 제공되는 페이지에서만 작동 할 수 있습니다.


var $head = $("#eFormIFrame").contents().find("head");

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

iframe은 대부분의 브라우저에서 일반적으로 다른 HTML 페이지처럼 처리됩니다. iframe의 콘텐츠에 동일한 스타일 시트를 적용하려면 여기에 사용 된 페이지에서 참조하면됩니다.


<link>추가 스타일 시트를로드 하지 않고 CSS 코드를 직접 적용하는 방법은 다음과 같습니다 .

var head = jQuery("#iframe").contents().find("head");
var css = '<style type="text/css">' +
          '#banner{display:none}; ' +
          '</style>';
jQuery(head).append(css);

iframe 페이지에서 배너를 숨 깁니다. 제안 해 주셔서 감사합니다!


hangy가 말했듯이 iframe에서 페이지를 제어하는 ​​경우 가장 쉬운 방법은 공통 스타일로 공유 CSS 파일을 만든 다음 html 페이지에서 링크하는 것입니다.

그렇지 않으면 iframe의 외부 페이지에서 페이지 스타일을 동적으로 변경할 수 없을 것입니다. 이는 브라우저가 스푸핑 및 기타 해킹에 대한 오용 가능성으로 인해 크로스 프레임 돔 스크립팅에 대한 보안을 강화했기 때문입니다.

이 자습서 에서는 일반적인 iframe 스크립팅에 대한 자세한 정보를 제공 할 수 있습니다. 크로스 프레임 스크립팅 정보 는 IE 관점에서 보안 제한을 설명합니다.


약간의 변경 사항이있는 위의 작업 :

var cssLink = document.createElement("link") 
cssLink.href = "pFstylesEditor.css"; 
cssLink.rel = "stylesheet"; 
cssLink.type = "text/css"; 

//Instead of this
//frames['frame1'].document.body.appendChild(cssLink);
//Do this

var doc=document.getElementById("edit").contentWindow.document;

//If you are doing any dynamic writing do that first
doc.open();
doc.write(myData);
doc.close();

//Then append child
doc.body.appendChild(cssLink);

적어도 ff3 및 ie8에서 잘 작동합니다.


메인 페이지에서 CSS와 JavaScript를 재사용하고 싶다면 <IFRAME>Ajax로로드 된 콘텐츠로 교체 하는 것을 고려해야 합니다. 이것은 검색 봇이 JavaScript를 실행할 수있을 때 더 SEO 친화적입니다.

이것은 문서에 다른 html 페이지를 포함하는 jQuery 예제입니다. 이것은보다 SEO 친화적 iframe입니다. 봇이 포함 된 페이지의 색인을 생성하지 않도록하려면 해당 페이지를 추가하여robots.txt

<html>
  <header>
    <script src="/js/jquery.js" type="text/javascript"></script>
  </header>
  <body>
    <div id='include-from-outside'></div>
    <script type='text/javascript'>
      $('#include-from-outside').load('http://example.com/included.html');
    </script> 
  </body>
</html>

또한 Google에서 직접 jQuery를 포함 할 수도 있습니다. http://code.google.com/apis/ajaxlibs/documentation/- 이는 새로운 버전의 선택적 자동 포함과 상당한 속도 향상을 의미합니다. 또한 jQuery를 제공하기 위해 그들을 신뢰해야 함을 의미합니다.)


다음은 나를 위해 일했습니다.

var iframe = top.frames[name].document;
var css = '' +
          '<style type="text/css">' +
          'body{margin:0;padding:0;background:transparent}' +
          '</style>';
iframe.open();
iframe.write(css);
iframe.close();

컴팩트 버전 :

<script type="text/javascript">
$(window).load(function () {
    var frame = $('iframe').get(0);
    if (frame != null) {
        var frmHead = $(frame).contents().find('head');
        if (frmHead != null) {
            frmHead.append($('style, link[rel=stylesheet]').clone()); // clone existing css link
            //frmHead.append($("<link/>", { rel: "stylesheet", href: "/styles/style.css", type: "text/css" })); // or create css link yourself
        }
    }   
});
</script>

그러나 때로는 iframe창이로드 된 상태에서 준비되지 않았으므로 타이머를 사용해야 합니다 .

즉시 사용 가능한 코드 (타이머 포함) :

<script type="text/javascript">
var frameListener;
$(window).load(function () {
    frameListener = setInterval("frameLoaded()", 50);
});
function frameLoaded() {
    var frame = $('iframe').get(0);
    if (frame != null) {
        var frmHead = $(frame).contents().find('head');
        if (frmHead != null) {
            clearInterval(frameListener); // stop the listener
            frmHead.append($('style, link[rel=stylesheet]').clone()); // clone existing css link
            //frmHead.append($("<link/>", { rel: "stylesheet", href: "/styles/style.css", type: "text/css" })); // or create css link yourself
        }
    }
}
</script>

... 및 jQuery 링크 :

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js" type="text/javascript"></script>

위의 jQuery 솔루션을 확장하여 프레임 콘텐츠로드 지연에 대처합니다.

$('iframe').each(function(){
    function injectCSS(){
        $iframe.contents().find('head').append(
            $('<link/>', { rel: 'stylesheet', href: 'iframe.css', type: 'text/css' })
        );
    }

    var $iframe = $(this);
    $iframe.on('load', injectCSS);
    injectCSS();
});

"doc.open ()"이라고 말하면 iframe 안에 HTML 태그를 작성할 수 있으므로 HTML 페이지에 대한 모든 기본 태그를 작성해야하며 iframe 헤드에 CSS 링크를 포함하려면 CSS 링크가있는 iframe. 예를 들어 보겠습니다.

doc.open();

doc.write('<!DOCTYPE html><html><head><meta charset="utf-8"/><meta http-quiv="Content-Type" content="text/html; charset=utf-8"/><title>Print Frame</title><link rel="stylesheet" type="text/css" href="/css/print.css"/></head><body><table id="' + gridId + 'Printable' + '" class="print" >' + out + '</table></body></html>');

doc.close();

사용은 이것을 시도 할 수 있습니다 :

$('iframe').load( function() {
     $('iframe').contents().find("head")
     .append($("<style type='text/css'>  .my-class{display:none;}  </style>"));
  });

이런 식으로 iframe의 콘텐츠에 스타일을 지정할 수 없습니다. 내 제안은 서버 측 스크립팅 (PHP, ASP 또는 Perl 스크립트)을 사용하거나 피드를 JavaScript 코드로 변환 할 온라인 서비스를 찾는 것입니다. 이를 수행하는 유일한 다른 방법은 서버 측 포함을 수행 할 수있는 경우입니다.


여기에 다른 답변은 jQuery 및 CSS 링크를 사용하는 것 같습니다.

이 코드는 바닐라 자바 ​​스크립트를 사용합니다. 새로운 <style>요소를 생성합니다 . 해당 요소의 텍스트 콘텐츠를 새 CSS를 포함하는 문자열로 설정합니다. 그리고 해당 요소를 iframe 문서의 헤드에 직접 추가합니다.

var iframe = document.getElementById('the-iframe');
var style = document.createElement('style');
style.textContent =
  '.some-class-name {' +
  '  some-style-name: some-value;' +
  '}' 
;
iframe.contentDocument.head.appendChild(style);

iframe 페이지에 액세스 할 수 있고 페이지에서 iframe을 통해로드 할 때만 다른 CSS를 적용하려는 경우 여기에서 이러한 종류의 솔루션을 찾았습니다.

iframe이 다른 도메인을로드하는 경우에도 작동합니다.

확인하다 postMessage()

계획은 css를 iframe에 다음과 같은 메시지로 보내는 것입니다.

iframenode.postMessage('h2{color:red;}','*');

* iframe에있는 도메인에 관계없이이 메시지를 보내는 것입니다.

iframe에서 메시지를 수신하고 수신 된 메시지 (CSS)를 해당 문서 헤드에 추가합니다.

iframe 페이지에 추가 할 코드

window.addEventListener('message',function(e){

    if(e.data == 'send_user_details')
    document.head.appendChild('<style>'+e.data+'</style>');

});

나는 이와 같이 메인 HTML에 스타일을 넣는 또 다른 해결책을 찾았습니다.

<style id="iframestyle">
    html {
        color: white;
        background: black;
    }
</style>
<style>
    html {
        color: initial;
        background: initial;
    }
    iframe {
        border: none;
    }
</style>

그런 다음 iframe에서 이것을 수행하십시오 (js onload 참조)

<iframe  onload="iframe.document.head.appendChild(ifstyle)" name="log" src="/upgrading.log"></iframe>

그리고 js에서

<script>
    ifstyle = document.getElementById('iframestyle')
    iframe = top.frames["log"];
</script>

It may not be the best solution, and it certainly can be improved, but it is another option if you want to keep a "style" tag in parent window


I think the easiest way is to add another div, in the same place as the iframe, then

make its z-index bigger than the iframe container, so you can easly just style your own div. If you need to click on it, just use pointer-events:none on your own div, so the iframe would be working in case you need to click on it ;)

I hope It will help someone ;)


We can insert style tag into iframe. Posted also here...

<style type="text/css" id="cssID">
.className
{
    background-color: red;
}
</style>

<iframe id="iFrameID"></iframe>

<script type="text/javascript">
    $(function () {
        $("#iFrameID").contents().find("head")[0].appendChild(cssID);
        //Or $("#iFrameID").contents().find("head")[0].appendChild($('#cssID')[0]);
    });
</script>

Here, There are two things inside the domain

  1. iFrame Section
  2. Page Loaded inside the iFrame

So you want to style those two sections as follows,

1. Style for the iFrame Section

It can style using CSS with that respected id or class name. You can just style it in your parent Style sheets also.

<style>
#my_iFrame{
height: 300px;
width: 100%;
position:absolute;
top:0;
left:0;
border: 1px black solid;
}
</style>

<iframe name='iframe1' id="my_iFrame" src="#" cellspacing="0"></iframe>

2. Style the Page Loaded inside the iFrame

This Styles can be loaded from the parent page with the help of Javascript

var cssFile  = document.createElement("link") 
cssFile.rel  = "stylesheet"; 
cssFile.type = "text/css"; 
cssFile.href = "iFramePage.css"; 

then set that CSS file to the respected iFrame section

//to Load in the Body Part
frames['my_iFrame'].document.body.appendChild(cssFile); 
//to Load in the Head Part
frames['my_iFrame'].document.head.appendChild(cssFile);

Here, You can edit the Head Part of the Page inside the iFrame using this way also

var $iFrameHead = $("#my_iFrame").contents().find("head");
$iFrameHead.append(
   $("<link/>",{ 
      rel: "stylesheet", 
      href: urlPath, 
      type: "text/css" }
     ));

There is a wonderful script that replaces a node with an iframe version of itself. CodePen Demo

enter image description here

Usage Examples:

// Single node
var component = document.querySelector('.component');
var iframe = iframify(component);

// Collection of nodes
var components = document.querySelectorAll('.component');
var iframes = Array.prototype.map.call(components, function (component) {
  return iframify(component, {});
});

// With options
var component = document.querySelector('.component');
var iframe = iframify(component, {
  headExtra: '<style>.component { color: red; }</style>',
  metaViewport: '<meta name="viewport" content="width=device-width">'
});

var link1 = document.createElement('link');
    link1.type = 'text/css';
    link1.rel = 'stylesheet';
    link1.href = "../../assets/css/normalize.css";
window.frames['richTextField'].document.body.appendChild(link1);


As an alternative, you can use CSS-in-JS technology, like below lib:

https://github.com/cssobj/cssobj

It can inject JS object as CSS to iframe, dynamically


This is just a concept, but don't implement this without security checks and filtering! Otherwise script could hack your site!

Answer: if you control target site, you can setup the receiver script like:

1) set the iframe link with style parameter, like:

http://your_site.com/target.php?color=red

(the last phrase is a{color:red} encoded by urlencode function.

2) set the receiver page target.php like this:

<head>
..........
$col = FILTER_VAR(SANITIZE_STRING, $_GET['color']);
<style>.xyz{color: <?php echo (in_array( $col, ['red','yellow','green'])?  $col : "black") ;?> } </style>
..........

Well, I have followed these steps:

  1. Div with a class to hold iframe
  2. Add iframe to the div.
  3. In CSS file,
divClass { width: 500px; height: 500px; }
divClass iframe { width: 100%; height: 100%; }

This works in IE 6. Should work in other browsers, do check!

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

반응형