JavaScript enables ifram to access and communicate with PHP instances across domains, and javascriptifram

Source: Internet
Author: User

JavaScript enables ifram to access and communicate with PHP instances across domains, and javascriptifram

Mutual access between iframe and the main framework

1. Mutual access between the same domain

Assume that both a.html and B .html domain are localhost (same domain)
In A.html, iframe is embedded into B .html, name = myframe
A.html has js function fMain ()
B .html has js function named rame ()
A.html needs to be implemented to call B .html's javasrame(example, B .html calls A.html's fMain ()

A.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 

B .html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 

Click the exec iframe function button in a.html and run it successfully. The iframe function execute success is displayed. For example

Click the exec main function button in B .html and run it successfully. The main function execute success is displayed. For example

2. Cross-origin access

Assume that A.html domain is localhost and B .html domain is 127.0.0.1 (cross-origin)
The use of localhost and 127.0.0.1 is only convenient for testing. localhost and 127.0.0.1 are different from each other, so the execution effect is the same.
In actual use, change to www.domaina.com and www.domainb.com.
In A.html, iframe is embedded into B .html, name = myframe
A.html has js function fMain ()
B .html has js function named rame ()
A.html needs to call B .html's javasrame(example, B .html calls A.html's fMain () (cross-origin call)

If you use the same region, the browser returns an error message when the.html and B .html fields are different.
Uncaught SecurityError: Blocked a frame with origin "http: // localhost" from accessing a frame with origin "http: // 127.0.0.1". Protocols, domains, and ports must match.

Implementation principle:
The browser prohibits access from different domains for security purposes. Therefore, as long as both parties call and execute the same domain, they can access each other.

First, how can a.html use the fIframe method of B .html?
1.create an iframe in a.html
2. Put the iframe page in the B .html domain and name it execb.html.
3.execB.html is a js call that calls the B .html extension rame method.

<script type="text/javascript"> parent.window.myframe.fIframe(); // execute parent myframe fIframe function </script> 

In this example, a.html can call the fIframe method of B .html through execB.html.

Likewise, B .html uses a.html fmain.pdf to embed the execA.html file in the same domain as a.html in B .html.
ExecA.html contains js calls that call the.html fMain method.

<script type="text/javascript"> parent.parent.fMain(); // execute main function </script> 

In this way, A.html and B .html can be called across domains.

A.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 

B .html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 

ExecA.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 

ExecB.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 

Example:


Communication class between php main and iframe (same domain/cross-domain)
The main and iframe communication methods are encapsulated into classes. There are mainly two files,
JS: FrameMessage. js implements the interface for calling methods. For example, if cross-origin is used, a temporary iframe is created and the same-domain executor is called.
PHP: FrameMessage. class. php returns the JS code of the execution method based on the parameters when receiving cross-origin requests.

Functions:
1. support communication between the same domain and Cross-Domain Communication
2. The passed method parameters support strings, JSON, arrays, and so on.

Copy codeThe Code is as follows: FrameMessage.exe c ('HTTP: // 127.0.0.1/execB. php', 'myframework', 'invalid rame', ['fdipzone ',' {"gender": "male", "age": "29 "}', '["http://blog.csdn.net/fdipzone", "http://weibo.com/fdipzone"]']);

Copy codeThe Code is as follows: FrameMessage.exe c ('HTTP: // localhost/execA. php ', '', 'fmain', ['grammer', '{" first ":" PHP "," second ":" javascript "}', '["EEG", "NMG"]']);

FrameMessage. js

/** Main and Iframe Communication classes support communication between the same domain and Cross-Domain Communication * Date: * Author: fdipzone * Ver: 1.0 */var FrameMessage = (function () {this. oFrameMessageExec = null; // temporary iframe/* execution method executor execution page. If it is null, it indicates the framework name of the method to be called by the frame in the same domain, if it is null, It is the parameter of the method to be called by parent func. It must be an array [arg1, arg2, arg3, argn...], make it easy to use the apply call element in string format. Do not use html. The injection security issue will filter */this.exe c = function (executor, frame, func, args) {this.exe cutor = typeof (e Xecutor )! = 'Undefined '? Executor: ''; this. frame = typeof (frame )! = 'Undefined '? Frame: ''; this. func = typeof (func )! = 'Undefined '? Func: ''; this. args = typeof (args )! = 'Undefined '? (_ FIsArray (args )? Args: []): []; // it must be an array if (executor = '') {_ fSameDomainExec (); // same domain} else {_ fCrossDomainExec (); // cross domain}/* same domain execution */function _ fSameDomainExec () {if (this. frame = '') {// parent. window [this. func]. apply (this, this. args);} else {window. frames [this. frame] [this. func]. apply (this, this. args) ;}}/* cross-origin execution */function _ fCrossDomainExec () {if (this. oFrameMessageExec = null) {t His. oFrameMessageExec = document. createElement ('iframe'); this. oFrameMessageExec. name = 'framemessage _ tmp_frame '; this. oFrameMessageExec. src = _ fGetSrc (); this. oFrameMessageExec. style. display = 'none'; document. body. appendChild (this. oFrameMessageExec);} else {this. oFrameMessageExec. src = _ fGetSrc () ;}/ * Get the executed url */function _ fGetSrc () {return this.exe cutor + (this.exe cutor. indexOf ('? ') =-1? '? ':' & ') + 'Frame =' + this. frame + '& func =' + this. func + '& args =' + JSON. stringify (this. args) + '& framemessage_rand =' + Math. random ();}/* determines whether an array */function _ fIsArray (obj) {return Object. prototype. toString. call (obj) = '[object Array]';} return this ;}());

FrameMessage. class. php

<? Php/** Frame Message class main and iframe Communication classes * Date: * Author: fdipzone * Ver: 1.0 ** Func: * public execute creates the returned javascript * private jsFormat escape parameter */class FrameMessage */class start/* execute according to the parameter call Method * @ param String $ frame framework name of the method to be called, if it is null, It is parent * @ param String $ func. Name of the method to be called * @ param JSONstr $ parameter of the method to be called by args * @ return String */public static function. Execute ($ frame, $ func, $ args = '') {if (! Is_string ($ frame) |! Is_string ($ func) |! Is_string ($ args) {return '';} // frame and func can only contain letters, numbers, underscores (if ($ frame! = ''&&! Preg_match ('/^ [A-Za-z0-9 _] + $/', $ frame) |! Preg_match ('/^ [A-Za-z0-9 _] + $/', $ func) {return '';} $ params_str =''; if ($ args) {$ params = json_decode ($ args, true); if (is_array ($ params) {for ($ I = 0, $ len = count ($ params ); $ I <$ len; $ I ++) {// filter parameters to prevent injection of $ params [$ I] = self: jsFormat ($ params [$ I]);} $ params_str = "'". implode ("','", $ params ). "'" ;}} if ($ frame = '') {// parent return self: returnJs (" parent. parent. ". $ func. "(". $ params_str. ");");} else {retu Rn self: returnJs ("parent. window. ". $ frame. ". ". $ func. "(". $ params_str. ");") ;}}/** create the returned javascript * @ param String $ str * @ return String */private static function returnJs ($ str) {$ ret = '<script type = "text/javascript"> '. "\ r \ n"; $ ret. = $ str. "\ r \ n"; $ ret. = '</script>'; return $ ret;}/** escape parameter * @ param String $ str * @ return String */private static function jsFormat ($ str) {$ str = strip_tags (trim ($ Str); // filter html $ str = str_replace ('\ s \ s',' \ s', $ str ); $ str = str_replace (chr (10), '', $ str); $ str = str_replace (chr (13),'', $ str ); $ str = str_replace ('','', $ str); $ str = str_replace ('\', '\', $ str ); $ str = str_replace ('"', '\"', $ str); $ str = str_replace ('\\\'','\\\\\'', $ str); $ str = str_replace ("'", "\'", $ str); return $ str ;}// class end?>

A.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 

ExecA. php and execB. php

<?php require 'FrameMessage.class.php';  $frame = isset($_GET['frame'])? $_GET['frame'] : ''; $func = isset($_GET['func'])? $_GET['func'] : ''; $args = isset($_GET['args'])? $_GET['args'] : '';  $result = FrameMessage::execute($frame, $func, $args);  echo $result; ?> 

Articles you may be interested in:
  • Solution to the failure of jssdk on the iframe page
  • JavaScript Enables automatic iframe height adjustment and cross-origin of different primary domain names
  • Implementation of the JavaScript iframe data sharing interface
  • Js Method for checking whether iframe is loaded
  • Js implementation to prevent iframe
  • How to use JavaScript to control homepage redirection in iframe
  • How to obtain the longdesc attribute in iframe using JS
  • Mutual Operation Analysis of JavaScript iframe
  • JavaScript code for dynamically adjusting the height of iframe
  • Real iframe highly adaptive implemented by js (compatible with IE, FF, and Opera)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.