简体   繁体   中英

Can I access javascripts from iframe parent on another domain

I control both domains and could set whatever policies necessary. The domain in the iframe uses pretty much the same libraries and I was hoping to leech them off the parent if possible.

To be clear, I'm not asking how to make a cross-domain request. I'm asking how to get scripts from an iframe's parent, when the parent is on another domain.

I'm getting a permission error with this (trying jQuery here but same with my other libraries):

if (typeof(jQuery) == "undefined") {
  var iframebody = document.getElementsByTagName("body")[0];
  var jQuery = function (selector) { return parent.jQuery(selector, iframebody); };
  var $ = jQuery;
}
$("<h1>Hello World</h1>").appendTo("body");

This would work if they were on the same domain.

I know this is cross-domain and is blocked for security reasons, but considering I control both domains and neither are security sensitive, I could set any policies as lax as I want to.

Can this be done?

If you include the js from the same source in both pages, it will be just loaded once, but will be accessible on both sites:

//parent/main.html
<script src="jquery.js"></script>
<iframe src="http://other/iframe.html"></iframe>
<script>
  $(document.body).html("wohoo");
</script>

//other/iframe.html
 <script src="http://parent/jquery.js"></script>
<script>
  $(document.body).html("wohoo");
</script>

So if theyre accessed in the iframe, the script is just loaded once, and if you access each of them without the other, it will still work too.

You can use postMessage to pass information back and forth between frames and their parent window.

https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

You'll have to run the code to modify the element in the domain where it lives, but you can set a post message handlerler in the parent to kick it off.

// child window (iframe content)
parent.postMessage("hi there", "https://parent.domain.here");


// parent window
window.addEventListener("message", function(message){
    $("<h1>"+message+"</h1>").appendTo("body");
});

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