Securityerror: Blocked a Frame with Origin from Accessing a Cross-Origin Frame

I am loading an <iframe> in my HTML page and trying to access the elements within it using Javascript, but when I try to execute my code, I get the following error:

SecurityError: Blocked a frame with origin "" from accessing a cross-origin frame.

Can you please help me to find a solution so that I can access the elements in the frame?

I am using this code for testing, but in vain:

$(document).ready(function() {
    var iframeWindow = document.getElementById("my-iframe-id").contentWindow;

    iframeWindow.addEventListener("load", function() {
        var doc = iframe.contentDocument || iframe.contentWindow.document;
        var target = doc.getElementById("my-target-id");

        target.innerHTML = "Found it!";
    });
});
1

9 Answers

Same-origin policy

You can't access an <iframe> with different origin using JavaScript, it would be a huge security flaw if you could do it. For the same-origin policy browsers block scripts trying to access a frame with a different origin.

Origin is considered different if at least one of the following parts of the address isn't maintained:

protocol://hostname:port/...

Protocol, hostname and port must be the same of your domain if you want to access a frame.

NOTE: Internet Explorer is known to not strictly follow this rule, see here for details.

Examples

Here's what would happen trying to access the following URLs from

URL                                             RESULT 
       -> Success 
 -> Success 
                    -> Success (default port for HTTP) 
                  -> Failure: different port 
       -> Failure: different hostname 
   -> Failure: different protocol
ftp://                     -> Failure: different protocol & port 
       -> Failure: different protocol, port & hostname 
Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.