摘要:本文主要向大家介绍了PHP语言 main 与 iframe 相互通讯类(同域、跨域),通过具体的实例向大家展示,希望对大家学习php语言有所帮助。
本文主要向大家介绍了PHP语言 main 与 iframe 相互通讯类(同域、跨域),通过具体的实例向大家展示,希望对大家学习php语言有所帮助。
main 与 iframe 相互通讯类
之前写过一篇《iframe与主框架跨域相互访问方法》,介绍了main与iframe相互通讯的原理,不了解原理的可以先看看。
今天把main与iframe相互通讯的方法封装成类,主要有两个文件,
JS:FrameMessage.js 实现调用方法的接口,如跨域则创建临时iframe,调用同域执行者。
PHP:FrameMessage.class.php 实现接收到跨域请求时,根据参数返回执行方法的JS code。
功能如下:
1.支持同域与跨域通讯
2.传递的方法参数支持字符串,JSON,数组等。
[javascript] view plain copy
1. FrameMessage.exec('//127.0.0.1/execB.php', 'myframe', 'fIframe', ['fdipzone', '{"gender":"male","age":"29"}', '["//blog.csdn.net/fdipzone", "//weibo.com/fdipzone"]']);
[javascript] view plain copy
1. FrameMessage.exec('//localhost/execA.php', '', 'fMain', ['programmer', '{"first":"PHP","second":"javascript"}', '["EEG","NMG"]']);
因部分浏览器不支持JSON.stringify 与JSON.parse 方法(如IE6/7),为了兼容,需要包含json2.js,下载地址:https://github.com/douglascrockford/JSON-js
FrameMessage.js
[javascript] view plain copy
1. /** Main 与 Iframe 相互通讯类 支持同域与跨域通讯
2. * Date: 2013-12-29
3. * Author: fdipzone
4. * Ver: 1.0
5. */
6. var FrameMessage = (function(){
7.
8. this.oFrameMessageExec = null; // 临时iframe
9.
10. /* 执行方法
11. executor 执行的页面,为空则为同域
12. frame 要调用的方法的框架名称,为空则为parent
13. func 要调用的方法名
14. args 要调用的方法的参数,必须为数组[arg1, arg2, arg3, argn...],方便apply调用
15. 元素为字符串格式,请不要使用html,考虑注入安全的问题会过滤
16. */
17. this.exec = function(executor, frame, func, args){
18.
19. this.executor = typeof(executor)!='undefined'? executor : '';
20. this.frame = typeof(frame)!='undefined'? frame : '';
21. this.func = typeof(func)!='undefined'? func : '';
22. this.args = typeof(args)!='undefined'? (__fIsArray(args)? args : []) : []; // 必须是数组
23.
24. if(executor==''){
25. __fSameDomainExec(); // same domain
26. }else{
27. __fCrossDomainExec(); // cross domain
28. }
29.
30. }
31.
32. /* 同域执行 */
33. function __fSameDomainExec(){
34. if(this.frame==''){ // parent
35. parent.window[this.func].apply(this, this.args);
36. }else{
37. window.frames[this.frame][this.func].apply(this, this.args);
38. }
39. }
40.
41. /* 跨域执行 */
42. function __fCrossDomainExec(){
43. if(this.oFrameMessageExec == null){
44. this.oFrameMessageExec = document.createElement('iframe');
45. this.oFrameMessageExec.name = 'FrameMessage_tmp_frame';
46. this.oFrameMessageExec.src = __fGetSrc();
47. this.oFrameMessageExec.style.display = 'none';
48. document.body.appendChild(this.oFrameMessageExec);
49. }else{
50. this.oFrameMessageExec.src = __fGetSrc();
51. }
52. }
53.
54. /* 获取执行的url */
55. function __fGetSrc(){
56. return this.executor + (this.executor.indexOf('?')==-1? '?' : '&') + 'frame=' + this.frame + '&func=' + this.func + '&args=' + JSON.stringify(this.args) + '&framemessage_rand=' + Math.random();
57. }
58.
59. /* 判断是否数组 */
60. function __fIsArray(obj){
61. return Object.prototype.toString.call(obj) === '[object Array]';
62. }
63.
64. return this;
65.
66. }());
FrameMessage.class.php
[php] view plain copy
1. <?php
2. /** Frame Message class main 与 iframe 相互通讯类
3. * Date: 2013-12-29
4. * Author: fdipzone
5. * Ver: 1.0
6. *
7. * Func:
8. * public execute 根据参数调用方法
9. * private returnJs 创建返回的javascript
10. * private jsFormat 转义参数
11. */
12.
13. class FrameMessage{ // class start
14.
15. /* execute 根据参数调用方法
16. * @param String $frame 要调用的方法的框架名称,为空则为parent
17. * @param String $func 要调用的方法名
18. * @param JSONstr $args 要调用的方法的参数
19. * @return String
20. */
21. public static function execute($frame, $func, $args=''){
22.
23. if(!is_string($frame) || !is_string($func) || !is_string($args)){
24. return '';
25. }
26.
27. // frame 与 func 限制只能是字母数字下划线
28. if(($frame!='' && !preg_match('/^[A-Za-z0-9_]+$/',$frame)) || !preg_match('/^[A-Za-z0-9_]+$/',$func)){
29. return '';
30. }
31.
32. $params_str = '';
33.
34. if($args){
35. $params = json_decode($args, true);
36.
37. if(is_array($params)){
38.
39. for($i=0,$len=count($params); $i<$len; $i++){ // 过滤参数,防止注入
40. $params[$i] = self::jsFormat($params[$i]);
41. }
42.
43. $params_str = "'".implode("','", $params)."'";
44. }
45. }
46.
47. if($frame==''){ // parent
48. return self::returnJs("parent.parent.".$func."(".$params_str.");");
49. }else{
50. return self::returnJs("parent.window.".$frame.".".$func."(".$params_str.");");
51. }
52.
53. }
54.
55.
56. /** 创建返回的javascript
57. * @param String $str
58. * @return String
59. */
60. private static function returnJs($str){
61.
62. $ret = '<script type="text/javascript">'."\r\n";
63. $ret .= $str."\r\n";
64. $ret .= '</script>';
65.
66. return $ret;
67. }
68.
69.
70. /** 转义参数
71. * @param String $str
72. * @return String
73. */
74. private static function jsFormat($str){
75.
76. $str = strip_tags(trim($str)); // 过滤html
77. $str = str_replace('\\s\\s', '\\s', $str);
78. $str = str_replace(chr(10), '', $str);
79. $str = str_replace(chr(13), '', $str);
80. $str = str_replace(' ', '', $str);
81. $str = str_replace('\\', '\\\\', $str);
82. $str = str_replace('"', '\\"', $str);
83. $str = str_replace('\\\'', '\\\\\'', $str);
84. $str = str_replace("'", "\'", $str);
85.
86. return $str;
87. }
88.
89. } // class end
90.
91. ?>
A.html
[html] view plain copy
1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "//www.w3.org/TR/html4/loose.dtd">
2. <html>
3. <head>
4. <meta http-equiv="content-type" content="text/html; charset=utf-8">
5. <title> main window </title>
6. <script type="text/javascript" src="json2.js"></script>
7. <script type="text/javascript" src="FrameMessage.js"></script>
8.
9. <script type="text/javascript">
10.
11. // main js function
12. function fMain(profession, skill, company){
13.
14. var skill_p = JSON.parse(skill);
15. var company_p = JSON.parse(company);
16.
17. var msg = "main function execute success\n\n";
18. msg += "profession:" + profession + "\n";
19. msg += "first skill:" + skill_p.first + "\n";
20. msg += "second skill:" + skill_p.second + "\n";
21. msg += "company1:" + company_p[0] + "\n";
22. msg += "company2:" + company_p[1] + "\n";
23.
24. alert(msg);
25.
26. }
27.
28. // exec iframe function
29. function exec_iframe(){
30. // same domain
31. //FrameMessage.exec('', 'myframe', 'fIframe', ['fdipzone', '{"gender":"male","age":"29"}', '["//blog.csdn.net/fdipzone", "//weibo.com/fdipzone"]']);
32.
33. // cross domain
34. FrameMessage.exec('//127.0.0.1/execB.php', 'myframe', 'fIframe', ['fdipzone', '{"gender":"male","age":"29"}', '["//blog.csdn.net/fdipzone", "//weibo.com/fdipzone"]']);
35. }
36. </script>
37.
38. </head>
39.
40. <body>
41. <p>A.html main</p>
42. <p><input type="button" value="exec iframe function" onclick="exec_iframe()"></p>
43. <!-- same domain -->
44. <!--<iframe src="B.html" name="myframe" width="500" height="100"></iframe>-->
45. <!-- cross domain -->
46. <iframe src="//127.0.0.1/B.html" name="myframe" width="500" height="100"></iframe>
47. </body>
48. </html>
B.html
[html] view plain copy
1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "//www.w3.org/TR/html4/loose.dtd">
2. <html>
3. <head>
4. <meta http-equiv="content-type" content="text/html; charset=utf-8">
5. <title> iframe window </title>
6. <script type="text/javascript" src="json2.js"></script>
7. <script type="text/javascript" src="FrameMessage.js"></script>
8.
9. <script type="text/javascript">
10.
11. // iframe js function
12. function fIframe(name, obj, arr){
13.
14. var obj_p = JSON.parse(obj);
15. var arr_p = JSON.parse(arr);
16.
17. var msg = "iframe function execute success\n\n";
18. msg += "name:" + name + "\n";
19. msg += "gender:" + obj_p.gender + "\n";
20. msg += "age:" + obj_p.age + "\n";
21. msg += "blog:" + arr_p[0] + "\n";
22. msg += "weibo:" + arr_p[1] + "\n";
23.
24. alert(msg);
25.
26. }
27.
28. // exec main function
29. function exec_main(){
30. // same domain
31. //FrameMessage.exec('', '', 'fMain', ['programmer', '{"first":"PHP","second":"javascript"}', '["EEG","NMG"]']);
32.
33. // cross domain
34. FrameMessage.exec('//localhost/execA.php', '', 'fMain', ['programmer', '{"first":"PHP","second":"javascript"}', '["EEG","NMG"]']);
35. }
36. </script>
37.
38. </head>
39.
40. <body>
41. <p>B.html iframe</p>
42. <p><input type="button" value="exec main function" onclick="exec_main()"></p>
43. </body>
44. </html>
execA.php 与 execB.php
[php] view plain copy
1. <?php
2. require 'FrameMessage.class.php';
3.
4. $frame = isset($_GET['frame'])? $_GET['frame'] : '';
5. $func = isset($_GET['func'])? $_GET['func'] : '';
6. $args = isset($_GET['args'])? $_GET['args'] : '';
7.
8. $result = FrameMessage::execute($frame, $func, $args);
9.
10. echo $result;
11. ?>
本文由职坐标整理并发布,了解更多内容,请关注职坐标编程语言PHP频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号