简体   繁体   中英

Retrieving IFrame content using javascript

I have already received javascript code from this very website.

alert(window.frames['sc_frame'].document.getElementsByTagName('body')[0].innerHTML);

or

alert(window.frames['sc_frame'].document.getElementsByTagName('body')[0].innerText);

The problem is I am having this error.

Unsafe JavaScript attempt to access frame with URL http://xxxxxxxxxxxxxxxxxxxxxxxxxxxxx from frame with URL http://xxxxxxxxxxxxxxxxxxxxxxxxxxxxx. Domains, protocols and ports must match.
(anonymous function)
InjectedScript._evaluateOn
InjectedScript._evaluateAndWrap
InjectedScript.evaluate
TypeError: Cannot call method 'getElementsByTagName' of undefined
arguments: Array[2]
get message: function () { [native code] }
get stack: function () { [native code] }
set message: function () { [native code] }
set stack: function () { [native code] }
type: "non_object_property_call"
__proto__: Error

I also understand the cause as my IFrame is calling to another domain.

<iframe id="sc_frame" src="http://example1.com"></iframe>

I use the above code from http://example.com .

My question would be whether there is a workaround for this. either using javascript or any other methods?

You can not directly communicate with other elements in the body across domains (/ports/protocols) due to security constraints. Not only can't you access the target document source, you can't access the objects and events either.

What you can do, is use frameworks for sending messages across domains via a proxy. This answer talks about that.

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