I am writing a jQuery Plugin that needs to be able to run against DOM elements within an iFrame. I'm just testing this locally right now (ie url is file://.../example.html) and in Chrome I keep hitting SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin null from accessing a cross-origin frame. and in Safari I just get an empty document.
Given that both the parent file and the iFrame's file are coming off my local disk (in development) and will be coming off the same server (in production) I'd have thought that I'd not be subject to the cross-origin issues.
Is there a way I can convince the browser that my local files are actually of the same domain?
<aside>Interestingly in Safari, using the console directly, I can type $(iframe).get(0).contentDocument.find(ol)
and it happily finds my list. In Chrome this same line throws the security error just as if it were being executed.</aside>
Update
Based on the suggestions below I have fired up a simple local web-server to test this and am now not getting the cross-origin error - yay - but neither am I getting any content.
My Javascript looks like
$(document).ready(function(){
var myFrame = $(iframe),
myDocument = $(myFrame.get(0).contentDocument),
myElements;
myDocument.ready(function(){
myElements = myDocument.find(ul, ol);
console.debug(success - iFrame, myFrame, document, myDocument, elements, myElements);
});
});
The myDocument.ready
is there just to ensure that the iFrame's document is ready - in reality it makes no difference.
I always end up with myElements
being empty. ([]
in safari or jQuery.fn.init[0]
in Chrome)
But if I manually type this into the console:
$($(iframe).get(0).contentDocument).find(ol, ul)
I get my lists as expected. This is now the case in both Safari and Chrome.
So my question becomes: why can't my script see the DOM elements but the same code when entered directly into the browser's console can happily see the DOM elements?