Get value in an iframe via Javascript

1

I have code that is in an external file and need to load it via Javascript, however I do not know how to do it. I already tried it in several ways, and apparently it would be better with an iframe, but not that. The idea was to use the load () function of jQuery, but it has one detail: the code is being run locally, so this does not work because of HTTP and similar permissions. So I thought of doing an iframe like this:

<iframe id="iframe" src="script1.html"></iframe>

So I tried this way:

var text = $("#iframe").val();

It did not return anything, so I tagged the file and tried:

$('#iframe').contents().find("html").html();

Still, nothing. So I tried this way:

var iBody = $("#iframe").contents().find("body");
var myContent = iBody.find("#myContent");

The problem is that Chrome returns an error:

  Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "null" from accessing a frame with origin "null". Protocols, domains, and ports must match.

I mean, is there no way to load a file locally? I just need a clean file with the codes to load later, I'd even put it directly inside a tag inside the page, but that would get very dirty, since someone else will change the code. Note: This code that should be loaded I refer to is a text document, that is, you can interpret as you want, simply, are several phrases, nothing special about it.

    
asked by anonymous 29.03.2015 / 20:01

2 answers

1

This is not locally possible because of the protections that Browsers have.

You can get this to work if you have the file on a server and if the server in question accepts requests from other domains, otherwise the rule is the same.

This security rule is known as CORS (cross-source resource sharing) , a security recommendation of W3C that was adopted by the Browsers to prevent access to data unduly.

    
29.03.2015 / 20:18
0

Chrome does not allow you to load a file from the file system using XmlHttpRequest (Ajax). I even had this problem when testing HTML files with Ajax calls.

Each browser applies different rules for uploading same source files (CORS) when it comes to local files (uploaded via file://... , which is what happens when you double-click the HTML document in the folder).

I found some recommendations on running Chrome with the --allow-file-access-from-files flag, but I did not succeed.

To solve this problem, I created my own mini Web server that runs in a specific folder. You can try using Node.js to do something like this.

You can also try another browser that is less restrictive.

    
29.03.2015 / 20:17