简体   繁体   中英

How to apply css in iframe body content : Javascript

I used an iframe for some calculation like this.

<iframe id="iframe1" src="https://www.investwell.in/updation/parameter/Calculator/par_retirement_calculatorN.jsp?obgl=eeeeee&amp;fs=14&amp;ol=222222&amp;obgr=dddddddd&amp;or=111111&amp;share=N" width="100%" height="900" frameborder="0" scrolling="auto"></iframe>

Now, i want to apply css to iframe content using Javascript but i'm unable to get this.

JS:

$('iframe').load( function() {
    $('iframe').contents().find("head")
  .append($("<style type='text/css'>  .panel-body{background: red !important;}  </style>"));#000000';
});

Can anyone tell me where i'm going wrong here? Any help will be appreciated.

Thanks in advance.

You can't do that with an iframe. That would violate domain isolation ( Same origin policy ) and would be a massive security hole, as it would allow an attacker to modify portion of an arbitrary website after loading it. Imagine what I could do if I could modify arbitrary form data after loading your bank's website in a "handy" iframe for you!

The only way to do this would be to replace the iframe with a div, and load the content via javascript with an ajax request (which you can only do if the other page is also on your domain, or the appropriate CORS headers are set). Of course this would require extensive restructuring of both websites, and more importantly it would require you to have the permission of the target website which I don't suppose you do. Bear in mind that the same origin policy is in place exactly to prevent what you're trying to do, so there's no way around it.

I suggest you find another way to do whatever it is you're trying to do.

您不能,这是“ 同源来源”政策的一部分

You cannot change the style of a page displayed in an iframe unless you have direct access and therefore ownership of the source html and/or css files.

This is to stop XSS (Cross Site Scripting)

You can apply CSS for iframe content. Follow below steps.

  1. Create a Style Sheet according to your requirement.
  2. Create below JavaScript function in the main page.

      function myFunc() { var iframe = document.getElementById('iframe'); var style = document.createElement('link'); style.href = "CSS.css"; style.rel = "stylesheet"; style.type = "text/css"; iframe.contentDocument.head.appendChild(style); } 
  3. Call JavaScript function at onload event of iframe like below.

      <iframe id="iframe" src="test.html" width="100%"></iframe> 
  4. Enjoy :)

通过JavaScript不可能做到这一点。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM