I need to run an iframe on websites which will load in JavaScript for them to allow them to use a feature use on their webpage.
The iframe needs to be able to access the parent object so it can show and hide various things on the page.
Main html file:
<script type="text/javascript">
var SomeApi = {};
SomeApi.clickMe = function() {
//some event
}
</script>
Iframe:
<a href='#' onclick='parent.SomeApi.clickMe();return false;'>Click me</a>
I get the error:
SecurityError: Permission denied to access property "SomeApi" on cross-origin object
The iframe URL I am sending is using node.js express with the following headers:
app.use((req,res,next)=>{
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
What headers or configuration do I need to do so that I don't get the cross-origin object error and I can access the parent object?
The code will always be run on a different domain to the iframe.
As pointed out in the comments by Darkrum the issue wasn't with the headers as that's for XHR. I figured out the solution I required by doing a little workaround.
IFRAME html:
<iframe id='iframe-id' src='about:blank'></iframe>
I loaded the contents of the iframe using ajax
like so:
$.ajax({
url: "http://www.exampledomain.com",
success: function(data) {
$("#iframe-id").contents().find('body').html(data);
}
});
This allowed me to access the parent objects I required
<a href='#' onclick='parent.SomeApi.clickMe();return false;'>Click me</a>
I had to do this method as I required the contents to be in an iframe.
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.