Setting iframe src via JS isnt working specifically for sharepoint

Viewed 219

Setting src directly in iframe is working as expected

I'm trying to embed a Sharepoint document here.

For eg

<iframe src="https://rocketlane123-my.sharepoint.com/personal/lokeshkannan_rocketlane123_onmicrosoft_com/_layouts/15/Doc.aspx?sourcedoc={8822527b-0c56-44f9-8263-40c737db903c}&amp;action=embedview"
      width="476px"
      height="288px" />

Whereas when I set the src in the script it's failing

<iframe id="x" width="476px" height="288px"></iframe>

<script>
document.getElementById('x').src = "https://rocketlane123-my.sharepoint.com/personal/lokeshkannan_rocketlane123_onmicrosoft_com/_layouts/15/Doc.aspx?sourcedoc={8822527b-0c56-44f9-8263-40c737db903c}&amp;action=embedview";
</script>

Passing vs failing

This happens explicitly with SharePoint. So I would like to understand a couple of things here.

1. Am I doing something wrong?
2. Is there any CSP headers which block the parent from adding via JS?
3. Is there any official way from SharePoint to allow this? 
3. Is there any way to hack this?

Thanks in advance.

Since this happens across chrome, safari and firefox I think it's not a bug in a specific browser.

2 Answers

Trying this in Firefox yields this error message:

To protect your security, login.microsoftonline.com will not allow Firefox to display the page if another site has embedded it. To see this page, you need to open it in a new window.

Opening the console gives this message:

The loading of [url] in a frame is denied by “X-Frame-Options“ directive set to “DENY“.

This is a header that's set by login.microsoft.com to disable embedding the link as an iframe.

This link details this design choice: https://docs.microsoft.com/en-us/sharepoint/troubleshoot/sites/cannot-display-sharepoint-pages-in-iframe

The link mentions you can override the behavior by setting 'AllowFraming', though it doesn't recommend it, as there may be site-breaking changes by embedding it.

A guide to use this feature can be found at this link

The problem is in, javascript amp; should not represent as &.

Change your link to

<body>
    <iframe id="x" width="476px" height="288px"></iframe>
    
    <script>
    document.getElementById('x').src = "https://rocketlane123.sharepoint.com/sites/MyDocsforSP/_layouts/15/Doc.aspx?sourcedoc={6d327004-5d52-4e42-9707-c964631f8e65}&action=embedview";
    </script>
</body>
Related