Skip to content

.append() script string to iframe causes script execution in top window #4518

Closed

Description

index.html

<iframe id="frameID" width="200" height="200" srcdoc="<html><body></body></html>"></iframe>
  <script>
    var hello = 'hello';
    window.onload = function() {
      var script = "<script type=\"text\/javascript\" src=\"script.js\" async=\"async\"><\/script>";
      $('#frameID').contents().find('body').append(script);
    }
</script>

script.js

alert(hello)

I expect the script is executed in iframe body

Activity

  1. ghost changed the title [-]append script string to iframe causes script execution on root body using .append()[/-] [+].append() script string to iframe causes script execution in top window[/+] on Oct 22, 2019
  2. aduggal007 commented on Jan 17, 2020

    @aduggal007

    Keep in mind the following things and your code would work

    1. Use src in place of srcdoc, because of lack of support among browsers for srcdoc
    2. If you need to modify the body, do so by modifying the src tag and not the contents()
    3. If you are referring to an external script make sure it's using https: and not file:// as it will be blocked due to CORS

    The final working code is:

    <iframe id="frameID" src="data:text/html;charset=utf-8,<html><body>hi</body></html>"></iframe>
    <script>
    $(document).ready(function() {
    //could be replace by an external script like%3cscript src="link_of_the_script"%3E%3C/script%3E
    var script = "%3Cscript%3Edocument.write(1);%3C/script%3E";
    //get the contents of the src attribute
    var srcAttribute = $("#frameID")[0].src;
    //find index where you want to add the script
    var beginningIndex = srcAttribute.indexOf("<body>");
    //change the src attribute of iframe
    $("#frameID")[0].src = [srcAttribute.slice(0,beginningIndex+6),script,srcAttribute.slice(beginningIndex+6)].join(''); });
    </script>

  3. self-assigned this
    on Jan 20, 2020
  4. added this to the 3.5.0 milestone on Jan 20, 2020
  5. added a commit that references this issue on Feb 3, 2020
    4a62637
  6. mgol commented on Feb 3, 2020

    @mgol
    Member

    PR: #4601

  7. added 2 commits that reference this issue on Feb 3, 2020
    5d9974b
    90f9135
  8. added 2 commits that reference this issue on Feb 10, 2020
    4592595
    3dedc3f
  9. locked as resolved and limited conversation to collaborators on Sep 25, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions