I want to write a message in an iframe
, then reverse it by the submit
button and send it to the parent window, I have the reverse function but I don't know how to use window.parent.postMessage
for this job.
reverse_service.html (iframe- child)
<!DOCTYPE html>
<html>
<body>
<input type="text" id="myInput" >
<button onclick="reverseString()">submit</button>
<script>
function reverseString() {
var str = document.getElementById("myInput").value;
var splitString = str.split("");
var reverseArray = splitString.reverse();
var joinArray = reverseArray.join("");
return joinArray;}
window.parent.postMessage(reverseString(), "*" )
</script>
</body>
</html>
parent.html
<!DOCTYPE html>
<html>
<head>
<title>User Actions</title>
<meta charset="utf-8">
<script src="lib/jquery-3.2.1.min.js"></script>
<script>
/* global $ */
$(document).ready(function() {
'use strict';
$(window).on('message', function(evt) {
//Note that messages from all origins are accepted
//Get data from sent message
var data = evt.originalEvent.data;
//Create a new list item based on the data
var newItem = '\n\t<li>' + (data.payload || '') + '</li>';
//Add the item to the beginning of the actions list
$('#actions').prepend(newItem);
});
});
</script>
</head>
<body>
<iframe id="encoder_iframe" src="reverser_service.html"></iframe>
<ul id="actions">
</ul>
</body>
</html>