乐闻世界logo
搜索文章和话题

How to pass value to iframe from a window

3个答案

1
2
3

In web development, sometimes we need to pass parameters between different iframes and the parent page (or main window). This can be achieved in multiple ways, and here are some common methods:

1. URL Parameters (Query Strings)

You can pass parameters by including query strings in the src attribute of the iframe. For example:

html
<iframe src="page.html?param1=value1&param2=value2" ></iframe>

Within the iframe, in the page page.html, you can use JavaScript to read URL parameters:

javascript
const urlParams = new URLSearchParams(window.location.search); const param1 = urlParams.get('param1'); // value1 const param2 = urlParams.get('param2'); // value2

2. JavaScript postMessage Method

The postMessage method enables secure cross-origin communication. The parent page can send messages to the iframe, and the iframe can send messages back to the parent page. For example, the parent page can send a message to the iframe as follows:

javascript
const iframe = document.getElementById('myIframe'); iframe.contentWindow.postMessage('Hello there!', '*');

Then, within the iframe, listen for message events:

javascript
window.addEventListener('message', (event) => { // Verify event.origin to ensure message source security // if (event.origin !== 'http://example.com') return; console.log('Received message:', event.data); });

3. window.name Property

The window.name property allows persisting string data across different pages. Set the name attribute of the iframe before it loads:

javascript
const iframe = document.createElement('iframe'); iframe.name = JSON.stringify({ param1: 'value1', param2: 'value2' }); document.body.appendChild(iframe); iframe.src = 'page.html';

Then, within the iframe page, access these parameters via window.name:

javascript
const params = JSON.parse(window.name);

4. Direct Access to iframe Content

If the iframe is on the same origin as the parent page, you can directly access its DOM using JavaScript:

javascript
const iframe = document.getElementById('myIframe'); const iframeDocument = iframe.contentDocument || iframe.contentWindow.document; iframeDocument.getElementById('someElement').textContent = 'New text content';

Example

Suppose we want to pass parameters to an iframe using the JavaScript postMessage method. Here's how:

Parent page code:

html
<!DOCTYPE html> <html> <head> <title>Parent Page</title> </head> <body> <iframe id="myIframe" src="iframePage.html" style="height:200px;width:100%;"></iframe> <script> const iframe = document.getElementById('myIframe'); const data = { param1: 'value1', param2: 'value2' }; // Ensure the iframe is fully loaded before sending data iframe.onload = function() { iframe.contentWindow.postMessage(JSON.stringify(data), '*'); }; </script> </body> </html>

iframe page code (iframePage.html):

html
<!DOCTYPE html> <html> <head> <title>Iframe Page</title> </head> <body> <div id="message">Waiting for message...</div> <script> window.addEventListener('message', (event) => { // Add validation for event.origin to ensure message source security // if (event.origin !== 'http://example.com') return; const data = JSON.parse(event.data); document.getElementById('message').textContent = 'Received param1: ' + data.param1; }); </script> </body> </html>

In practical applications, the choice of method depends on specific scenarios, such as cross-origin requirements and whether bidirectional communication is needed. When using postMessage, security is paramount, so always verify the message source and content.

2024年6月29日 12:07 回复

This is an alternative solution for frames originating from different domains.

javascript
var frame = /*the iframe DOM object*/; frame.contentWindow.postMessage({call:'sendValue', value: /*value*/}, /*frame domain url or '*'*/);

Within the frame itself:

javascript
window.addEventListener('message', function(event) { var origin = event.origin || event.originalEvent.origin; // For Chrome, the origin property is in the event.originalEvent object. if (origin !== /*the container's domain url*/) return; if (typeof event.data == 'object' && event.data.call=='sendValue') { // Do something with event.data.value; } }, false);

However, it is unclear which browsers support this feature.

2024年6月29日 12:07 回复

Depending on your specific situation, however, if the iframe can be placed after the main page has loaded, you can simply use a query string, as shown below:

html
<iframe src="some_page.html?somedata=5&more=bacon"></iframe>

Then somewhere in some_page.html:

javascript
<script> var params = location.href.split('?')[1].split('&'); data = {}; for (x in params) { data[params[x].split('=')[0]] = params[x].split('=')[1]; } </script>
2024年6月29日 12:07 回复

你的答案