简体   繁体   English

使用JavaScript在两个HTML页面之间传递消息

[英]Passing message between two html pages using javascript

I have two HTML pages: source.html and dest.html 我有两个HTML页面:source.html和dest.html

  • In source.html, I create some buttons (start, stop, pause ...) 在source.html中,我创建了一些按钮(开始,停止,暂停...)
  • In dest.html, I create a simple clock. 在dest.html中,我创建了一个简单的时钟。

Whenever I click on one of these buttons, the source will send a message to dest. 每当我单击这些按钮之一时,消息源就会向dest发送一条消息。 After being processed, the result (based on which button was pressed) will be sent back to the source. 处理后,结果(基于按下哪个按钮)将被发送回源。 I tried iframe, but it did not work for me. 我尝试使用iframe,但对我不起作用。 Are there any suggestions that do not use the client-server model? 有没有不使用客户端服务器模型的建议?

There is no way to do that if the windows are independent (without requests to server). 没有办法做到这一点,如果窗户是独立的(不请求到服务器)。 If the both windows aren't of any kind of frames. 如果两个窗口都不是任何类型的框架。 Because of security reasons. 由于安全原因。

But if you create dest.html window from source.html, you can use created the window's variable ( window.open ) to manage it and OPENER object to manage source.html window. 但是,如果您从source.html创建dest.html窗口,则可以使用创建的窗口变量( window.open )对其进行管理,而使用OPENER对象来管理source.html窗口。

There are 2 ways to send the message. 有两种发送消息的方法。

  1. In source create a form which submits to dest.html, make sure the method is 'GET' 在源代码中,创建一个提交给dest.html的表单,确保该方法为“ GET”

  2. On click of the button set the value of the message and submit the form 单击按钮时,设置消息的值并提交表格

    // something like document.getElementById('message').value = 'HELLO'; //类似于document.getElementById('message')。value ='HELLO'; document.getElementById('form').submit(); document.getElementById('form')。submit();

2a. 2a。 You dont need to make the form, you can just redirect with hardcoded url on the source.html button click like 您不需要填写表格,只需在source.html按钮上单击带有硬编码url的重定向,例如单击

window.location = 'dest.html?message=somemessage';
  1. On submit the dest.html file will open, with the message available in the URL of the page 提交后,将打开dest.html文件,并在页面的URL中提供消息。

    var url = window.location+""; var url = window.location +“”;

    // if there are multiple parameters you will have to loop and store them in array for single you can use //如果有多个参数,则必须循环并将它们存储在数组中,以便单个使用

    var message = url.substr((url.indexOf('=')+1)); var message = url.substr((url.indexOf('=')+ 1)); alert(message); 警报(消息);

2nd Method Not tried, store them in cookies when button gets clicked on source.html and read the cookies in dest.html 第2种方法没有试过,它们存储在cookie时按钮点击source.html获取和阅读dest.html饼干

Actually, you can. 其实可以。 Try to use the window.postMessage() method. 尝试使用window.postMessage()方法。 Plus, you will need to create an event listener if you want to post some message back. 另外,如果要发回一些消息,则需要创建一个事件侦听器。

Please follow the steps in this referrence 请按照此参考中的步骤进行操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM