cross domain image url in container to iframe input value - javascript

I have an iframe that I have control of posted into the container on a different domain.
I want to grab an image url in the parent container and insert it into aninput value in the iframe.
Here's my javascript code in the iframe:
<script>
function displayMessage (evt) {
var message;
if (evt.origin !== "https://container-url.com") {
message = "You are not worthy";
} else {
message = "testing";
}
document.getElementsByClassName('text')[2].setAttribute("value", message);
}
if (window.addEventListener) {
// For standards-compliant web browsers
window.addEventListener("message", displayMessage, false);
} else {
window.attachEvent("onmessage", displayMessage);
}
</script>
Here's my javascript in the <head> of the container:
<script>
window.onload = function () {
var iframeWin = document.getElementById("da-iframe").contentWindow,
myMessage = document.getElementsByClassName('portfolio_item_image wp-post-image')[0].src;
window.document.onload = function () {
iframeWin.postMessage(myMessage, "https://iframe-url.com");
return false;
};
};
</script>
Im trying to take the url of an image in the container that looks like this:
<img width="2000" height="1383" src="https://example.com/12.jpg," class="portfolio_item_image wp-post-image" alt="" srcset="https://example.com/123.jpg, https://example.com/1234.jpg," sizes="(max-width: 2000px) 100vw, 2000px">
and insert it into the value of an input in theiframe that looks like this:
<input type="text" name="505" id="505" value="" class="text" size="30" maxlength="65535">
I'm not getting any errors. I just cannot figure out what I'm doing wrong.

Related

Add localstorage link as a image src

Hello I have a local storage link that needs to be displayed as a img src. If the local storage link is google.com I want it to be displayed as a img src
code so far
<body>
<div id="result">
</div>
<img src="" id="photo" /> //this is the img element
<script>
if (typeof(Storage) !== "undefined") {
var name = localStorage.getItem('name');
var dataImage = localStorage.getItem('imgData');
document.getElementById("photo").innerHTML = localStorage.getItem("name"); //localstorage
} else {
document.getElementById("photo").innerHTML = "Sorry, your browser does not support Web Storage...";
}
</script>
</body>
I know this question is confusing but this is the best I could describe.
You can set the image src attribute to the value you get from local storage. (Assuming that's a path to an image)
You would not want to set the innerHTML of an img tag. Instead, use another element to display text.
<div id="result"></div>
<img src="" id="photo" /> //this is the img element
<div id="msg"></div>
<script>
if (typeof(Storage) !== "undefined") {
var name = localStorage.getItem('name');
var dataImage = localStorage.getItem('imgData');
var imageName = localStorage.getItem("name");
var imageEl = document.getElementById("photo");
imageEl.src = imageName
} else {
document.getElementById("msg").innerHTML = "Sorry, your browser does not support Web Storage...";
}
</script>

Get the iframe value

I have an iframe that I append User-written HTML, CSS, and JS code.
I can compile the code and return errors, but how can I get the actual result of the run?
for example, if the user-written code is BLAH it will return BLAH. so how can i get it?
I tried using this function:
var myIFrame = document.getElementById("test");
var content = myIFrame.contentWindow.document.body.innerHTML;
But it returns the tag.
The iframe is not cross-domain btw.
Code:
Iframe:
<div class="code-result">
<iframe class="result" id="test" frameborder="0"></iframe>
<div class="console"></div>
</div>
Js:
window.addEventListener('load',function() {
$(document).ready(
function (){
$('.compile').click(function () {
var myIFrame = document.getElementById("test");
var content = myIFrame.contentWindow.document.body.innerHTML;
html_result = content.substring(content.indexOf(0),content.indexOf('<script>'));
if (html_result == 'ds') {
alert('True!')
}
else {
alert('Try again.')
}
})
}
)
})

postMessage from an iframe opened in in new window

Please i have a small form that i open on a popop window like below.
<html>
<head>
</head>
<body>
<div id="popUpDiv" style="display:none;"></div>
<script type="text/javascript">
var popUpWindow;
function popup(n) {
popUpWindow = window.open("",n, "height=500,width=500");
}
function foo(obj){
test1 = "http://localhost:3001";
popUpWindow.document.write('<iframe height="450" id="receiver" allowTransparency="true" frameborder="0" scrolling="yes" style="width:100%;" src="'+test1+'" type= "text/javascript"></iframe>');
}
</script>
OnSale
</body>
</html>
above is the parent form and is running on the server localhost:3000. I opened new window with an iframe on it. I intend to postMessage from the popup or child window and receive it in the parent window. I then modified my code adding the onload below.
window.onload = function() {.
var messageEle = document.getElementById('message');
console.log('its receiving message');
function receiveMessage(e) {
alert('received');
console.log('the origin is ', e.origin);
if (e.origin !== "http://localhost:3001"){
return;
}
messageEle.innerHTML = "Message Received: " + e.data;
}
window.addEventListener('message', receiveMessage);
}
my complete parent page now looks like below.
<html>
<head>
</head>
<body>
<div id="popUpDiv" style="display:none;"></div>
<script type="text/javascript">
var popUpWindow;
function popup(n) {
popUpWindow = window.open("",n, "height=500,width=500");
}
function foo(obj){
test1 = "http://localhost:3001";
popUpWindow.document.write('<iframe height="450" id="receiver" allowTransparency="true" frameborder="0" scrolling="yes" style="width:100%;" src="'+test1+'" type= "text/javascript"></iframe>');
}
window.onload = function() {
var messageEle = document.getElementById('message');
console.log('its receiving message');
function receiveMessage(e) {
alert('received');
console.log('the origin is ', e.origin);
if (e.origin !== "http://localhost:3001"){
return;
}
messageEle.innerHTML = "Message Received: " + e.data;
}
window.addEventListener('message', receiveMessage);
}
</script>
OnSale
<div id="message"></div>
</body>
</html>
When i click the onSale link on the parent, it opened my child from the server 3001. However, running on the child console
parent.postMessage('Hello', 'http://localhost:3000');
does not fire the receiveMessage event of the parent. i confirmed my event is attached. I tried everything possible yet nothing change. Please what am i doing wrong ? any help would be appreciated
Sorry , after numerous attempt,
parent.opener.postMessage('Hello', 'http://localhost:3000');
Seems to work fine. Need to study the reason though . Found the answer here

IE losing iframe contents after back/forward key

This problem is only happening in IE (at least 8 and 9). After an element is dynamically added to the DOM, the contents of an embedded iframe are lost when the page is reentered with a BACK/FORWARD key. Just two small HTML files will reproduce the issue.
The first file is iframe.htm:
<!DOCTYPE html>
<html>
<head>
<title>IE iframe bug</title>
<script type="text/javascript">
function mytrace(msg) {
var t = document.createTextNode(msg);
var b = document.createElement('br');
var d = document.getElementById("trace_output")
d.appendChild(t);
d.appendChild(b); /// will work if commented
}
function submitListing() {
mytrace('submitListing()');
var doc = document.getElementById("output_iframe")
.contentWindow.document;
var d = new Date;
doc.location.replace('report.htm?invalidateCache=' + d.getTime());
//mytrace('submitListing(): out');
}
</script>
</head>
<body>
<div id="trace_output"><br /></div>
<input type="button" onclick="submitListing();" value="Run" /><br />
<iframe id="output_iframe" src=""></iframe>
</body>
</html>
The second file is report.htm:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
LINK
</body>
</html>
Steps to recreate the issue (BACK KEY)
Place above content in two files
Browse the iframe.htm file
Press the Run button to load report.htm in the iframe
Click on the LINK link to load a different page
Press the browser BACK button to returned to the "cached" (lmao) page
iframe contents are gone!!!! (only in IE-- safari, chrome, firefox retain the contents)
Also..(FORWARD KEY)
Browse to an arbitrary page (for history, http://www.google.com works)
Load iframe.htm into the same tab
Press the Run button to load report.htm in the iframe
Press the browser BACK button to return to the first page
Press the browser FORWARD button to return to iframe.htm
iframe contents are gone again!!
Now comment out the line:
d.appendChild(b)
That one change allows everything to work in IE. However, my solution needs to make those kinds of DOM manipulations (heavy jQuery/AJAX app) AND be able to restore the iframe across browser BACK/FORWARD actions.
It seems that I will have to remember the contents of the iframe so that I can restore it when the page is accessed with the BACK/FORWARD keys. I'm not thrilled with this because sometimes the iframe content will be quite large and it could chew up a bit of memory and time to make another copy of the embedded document for the restore. I would love to hear some other ideas about how I could approach this. Thanks in advance.
EDIT
The following replacement to iframe.htm will work around the problem with IE. I'm going to rewrite this using jQuery and add some more logic to restore the scroll positions. I had hoped for something more elegant, but this is doing the job.
<!DOCTYPE html>
<html>
<head>
<title>IE iframe bug</title>
<script type="text/javascript">
function myTrace(msg) {
var t = document.createTextNode(msg);
var b = document.createElement('br');
var d = document.getElementById("trace_output")
d.appendChild(t);
d.appendChild(b);
}
var make_backup ="false";
function submitListing() {
make_backup = "true";
myTrace('submitListing()');
var doc = document.getElementById("output_iframe").contentWindow.document;
var d = new Date;
doc.location.replace('report.htm?invalidateCache=' + d.getTime());
//myTrace('submitListing(): out');
}
function iframe_load() {
myTrace("iframe loaded, is_cached=" + document.getElementById("is_cached").value);
if (make_backup == "true") { // only when submitting
var htm, doc;
make_backup = "false"
doc = document.getElementById("output_iframe").contentWindow.document;
htm = doc.documentElement.innerHTML;
document.getElementById("iframe_backup").value = htmlEscape(htm);
}
}
function bodyLoaded() {
var is_cached = document.getElementById("is_cached");
if (is_cached.value == "false") { // initial page load
is_cached.value = "true";
}
else { // BACK or FORWARD, restore DOM where needed
var htm;
htm = htmlUnescape(document.getElementById("iframe_backup").value);
var doc;
doc = document.getElementById("output_iframe").contentWindow.document;
doc.open();
doc.writeln(htm);
doc.close();
}
}
function htmlEscape(str) {
return String(str).replace(/&/g, '&').replace(/"/g, '"')
.replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>');
}
function htmlUnescape(str) {
return String(str).replace(/&/g,'&').replace(/"/g,'"')
.replace(/'/g,"'").replace(/</g,'<').replace(/>/g,'>');
}
</script>
</head>
<body onload="bodyLoaded();">
<div id="trace_output" style="height: 300px; border-width:1; background-color: Silver"><br></div>
<input id="is_cached" type="hidden" value="false">
<input id="iframe_backup" type="hidden">
<input type="button" onclick="submitListing();" value="Run"><br>
<iframe id="output_iframe" src="" onload="iframe_load();"></iframe>
</body>
</html>
EDIT 2
Rewritten with jQuery:
<!DOCTYPE html>
<html>
<head>
<title>IE iframe workaround2</title>
<script type="text/javascript" src="Scripts/jquery-1.7.1.js"></script>
<script type="text/javascript">
var make_backup = "false";
$(document).ready(function () {
myTrace('document ready()');
var is_cached = $("#is_cached");
if (is_cached.val() == "false") { // initial page load
is_cached.val("true");
}
else { // BACK or FORWARD, restore DOM where needed
if ($.browser.msie) { // IE loses iframe content; restore
var htm = htmlUnescape($("#iframe_backup").val());
var doc = $("#output_iframe")[0].contentWindow.document;
doc.open();
doc.writeln(htm);
doc.close();
myTrace('iframe contents restored');
}
}
$('#output_iframe').load(function () {
myTrace("iframe_loaded");
if (make_backup == "true") { // only when submitting
make_backup = "false"
if ($.browser.msie) {
var doc = $("#output_iframe")[0].contentWindow.document;
var htm = doc.documentElement.innerHTML;
$("#iframe_backup").val(htmlEscape(htm));
myTrace('iframe contents backed up');
}
}
});
$('#submit_listing').click(function () {
make_backup = "true";
myTrace('submitListing()');
var doc = $("#output_iframe")[0].contentWindow.document;
var d = new Date;
doc.location.replace('report.htm?invalidateCache='+d.getTime());
});
});
function myTrace(msg) {
$('#trace_output').append(msg + '<br>');
}
function htmlEscape(str) {
return String(str).replace(/&/g, '&').replace(/"/g, '"')
.replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>');
}
function htmlUnescape(str) {
return String(str).replace(/&/g,'&').replace(/"/g,'"')
.replace(/'/g,"'").replace(/</g,'<').replace(/>/g,'>');
}
</script>
</head>
<body>
<div id="trace_output"
style="height: 300px; border-width:1; background-color: Silver">
<br></div>
<div style="display: block;">
<input id="is_cached" type="text" value="false">
<input id="iframe_backup" type="text" type="hidden"></div>
<input id="submit_listing" type="button" value="Run"><br>
<iframe id="output_iframe" src=""></iframe>
</body>
</html>

iframe location in javascript

In this example, alert is blank;
I want to read the location of iFrame, I am using object.src for this but it work only if I set its src attribute. But I set iFrame's location using window.open method and in this case it is not working. What I do ?
<body>
<iframe id="location" name="address" style="width:700px; height:700px;">
</iframe>
<script type="text/javascript" language="javascript">
window.open("http://www.google.com","address");
function clickMe()
{
var src = document.getElementBy Id("location").src;
alert(src);
}
</script>
<input type="button" onclick="clickMe()" value="click Me"/>
</body>
Instead of using window.open(), why don't you just use:
document.getElementById("location").src = "http://www.google.com";
Now you can get its location using getElementById()
You can do that by accessing the location.href attribute. Of course, for security reasons, browsers won't let you access the iframe's DOM if it's another domain.
var oIframe = document.getElementById("location");
// for compatibility
var oDoc = oIframe.contentWindow || oIframe.contentDocument;
if (oDoc.document) {
oDoc = oDoc.document;
}
alert(oDoc.location.href);
Same security issue if you access via the handle which should work in the same domain
<script>
var win;
function load(link) {
win=window.open(link.href,link.target)
return win?false:true;
}
function tell(winName) {
try {
alert(win.location.href)
try {
var handle = window.open('',winName);
alert(handle.location.href)
}
catch(e) {
alert('oops getting location via window handle:'+e.message)
}
}
catch(e) {
alert('Ooops getting location:'+e.message)
}
}
</script>
<iframe src="about:blank" name="if1"></iframe><br/>
Load foreign link<br />
Load local link<br />
Tell<br />

Categories