iframe submit get the posted content - javascript

Using an iframe to post a submit, it has a file upload. everything is working fine up til the returned content.
If i show the iframe on the page, i see the html that was returned from the function in my iframe. Having much trouble getting the content of the iframe to replace the content of the page.
Basically get the content of the body iframe and place it in the body tags of the page.
I'm sure its 1 or 2 lines, but every jquery or document or getElementById idea i've found on the web is not working.
I do notice something odd, if i try to use "console.info('somemessage')" in my reload function, it throws an error saying console does not exist. Not sure why, but seems my javascript focus is in the iframe and can't see firebug.
Heres the code stripped down. Back to trying the .load event, which is working. but its that second line that trys tot write the content to the body. when i comment it out, the iframe shows, with my content. If i run it uncommented, the whole page reloads.
if (isStarted == false) {
isStarted = true;
statustracker.start();
//style="height:0px;width:0px;"
var iframe = $('<iframe name="postframe" id="postframe" class="hidden" />');
$('div#iframe').append(iframe);
$('#ImportDetailForm').attr("target", "postframe")
form.submit();
$("#postframe").load(function () {
iframeContents = $("iframe")[0].contentDocument.body.innerHTML;
$("body").html(iframeContents); // <--- the problem
});
}

In your parent page (the one containing the iframe), you could set an event listener for the 'message' event, like so:
window.addEventListener("message", receiveMessage, false);
function receiveMessage(e) { ... }
Then in your iframe, just post a message to the 'parent' window like this:
parent.postMessage(someString, parentUrl);
Because messages are strings, you'll need to serialize any data you're sending between iframe and parent window - I suggest JSON! So in your case, serialize the returning HTML from the upload request and post it to the parent, then deserialize it on that side and inject it into the DOM.

An invalid or illegal string was specified" code: "12
probably because iframeContents is empty.
$("#postframe").load(function () {
var win = document.getElementById("postframe").contentWindow;
var parent_url = decodeURIComponent(document.location.hash.replace(/^#/, '')), link;
iframeContents = $("#postframe").find("body").contents().serialize(); //$("iframe")[0].contentDocument.body.innerHTML;
console.info(iframeContents);
//$(this).parent("body").html(iframeContents);
win.postMessage(iframeContents, parent_url, parent);
});

Related

How to fix getting the same document element 'meta' in Google Chrome Extension

I'm developing a new Chrome extension, that return meta of a website. My problem is that I have always the same result, even if the content of web page change. To get the correct and actual meta elements I must to refresh the tab (F5).
The code of my button is :
chrome.tabs.executeScript({file: 'app/js/get_metas.js'});
And the code of my get_metas.js is :
document.head.addEventListener("DOMContentLoaded", getMeta(), true);
function getMeta() {
const meta = document.head.querySelector("meta[property='****']").getAttribute("content");
alert(meta);
}
The result is always the same, I must refresh the page with F5 to get the actual meta element.
If you enter following code in your console you will see the alert immediately:
document.head.addEventListener("DOMContentLoaded", getMeta(), true);
function getMeta() {
alert("test");
}
Reason is that the function will be called immediately. To change that remove the (), and also I believe the event is fired on the document itself (I'm not sure the event traverses down the whole document and the useCapture=true would work). So use something like:
document.addEventListener("DOMContentLoaded", getMeta, true);
It will still only fire once when document is loaded. If you need to run the function after some other event you'd need to add a listener for that event.
If you want to call your function after a change to the document (including ajax navigation) you could look into using Mutation Observers.

Append() function working in chrome but NOT in firefox, Hierarchy error

Okay, so I have form information on a modal, and I need to close the modal (But not submit the form) and then open up another modal and then once they hit the submit button on THAT modal, it makes an AJAX call to a PHP file, with the old form.
I am doing this by taking the form information and moving the whole element to a hidden_div, and then I just append the info onto a form when I am ready.
Works on Chrome, doesn't work on Firefox.
switch_form_event = button.closest('.create-event-form');
hiddenDiv = $('#hidden_inner_div');
parent = switch_form_event.closest('.reveal');
hiddenDiv.attr("name", parent.id.toString());
switch_form_event.style.display = "none";
$(hiddenDiv).append($(switch_form_event)); //FAILS HERE
I have tried other things like: hiddenDiv += switch_form_event but that doesn't work.
The error I get is:
Node cannot be inserted at the specified point in the hierarchy
The node should just be form info without the form tags, aka: <input value='123'/> etc.
Both hiddenDiv and switch_form_event are already JQuery objects. Also, style is not a property of a jQuery object. It may be that your error is actually being caused by something else that you don't realize.
Try this:
switch_form_event = button.closest('.create-event-form');
hiddenDiv = $('#hidden_inner_div');
parent = switch_form_event.closest('.reveal');
hiddenDiv.attr("name", parent.id.toString());
switch_form_event.css("display", "none");
hiddenDiv.append(switch_form_event);
If that still doesn't work, please post the relevant HTML code.

Run javascript on website after refreshing

What I would like to achieve is this:
refresh website
run my javascript script on it (just as if I put it in Chrome console).
Question is: how to achieve it?
I can also use PHP for this (set server on my computer that wil be redirecting to the desired website and execute my javascript program on it).
Some example of functionality I want to achieve:
Go to stackoverflow.com -> click StackExchange (you can see it in the top left corner, it can be accessed by a querySelector() in JS) -> refresh stackoverflow.com -> click StackExchange again -> repeat...
If you want to refresh the page behind a DOM element click, you can attach an event handler to the element and then in your event handler execute location.reload() to reload the page.
//When the document has loaded, call the function
document.addEventListener("DOMContentLoaded", function(event) {
if(window.location.hash == "#page"){
console.log("Page reloaded!");
}else{
console.log("Page has a new hit!");
}
});
You can use DOMContentLoaded event listener to solve your problem.
You can do something like this -
var value = localStorage.getItem("logdata");
if(value != null) {
eval(value);
logdata();
}
And try to add logdata to localStorage from console.
Example - localStorage.setItem("logdata", "var logdata = function(e) { console.log('data logged.'); }");
Now when you load the page, logdata function will be called and you can have your code executed.

How to trigger iFrame load within an iFrame?

I send messages to iFrame, but only on iFrame load event. Want to trigger it manually without page reload, after changing DOM.
Explanation: It is kind of survey and on page change I send page size. Problem happens when I insert new image in DOM, than I need to tell parent page and trigger the iFrame load event. The message goes parent->iframe, than iframe->parent only on iFrame load.
Instead of triggering a load event, you should use a message posted by your IFrame.
JavaScript in outer frame (this attaches an event listener for messages and shows an alert when a message is received):
window.addEventListener('message', function(e) {
// This check can be removed for testing purposes, but for security
// it's strongly recommended that you leave it in there and replace
// the domain with the one of your IFrame's src, to ensure you process
// only messages coming from your own code and not somebody else's.
if(e.origin != "http://yourdomain.com") return;
alert("Got a message: " + e.data);
});
JavaScript in inner frame (this sends a message to the parent window - it should trigger the listener there and show the alert):
// The second parameter can be replaced by "*" for testing, but again it
// is strongly recommended to use the domain you expect the outer frame
// to have, to ensure your message lands in the right window (in case
// another page loaded yours in an IFrame).
window.parent.postMessage("Hello World!", "http://yourdomain.com");
Instead of "Hello World!", you can also pass JS objects.
It also works the other way round: If you install a message listener in your IFrame as well, then you can also send messages from the outer frame to the inner one, using something like document.getElementById('myIframe').contentWindow.postMessage(...).
See also: http://blog.teamtreehouse.com/cross-domain-messaging-with-postmessage

Javascript AJAX on a dynamicly loaded div?

How to add onload event to a div element?
I've read this, despite this I have a problem..
I know there's no onLoad for divs, but I should be able to execute a snippet like so:
...
<div id="content">
<div class="text">
</div>
</div>
<script type="text/javascript">
navigate('main.php', 'content');
</script>
....
This doesn't work, if I start a new browser session and navigate to index.php, it shows me a login window. After logging in it redirects me to index.php but with some session variables and cookies set. Now index.php contains the code above, prior to this content didn't exist.
Now to my issue: it appears as if most browsers refuses to accept that content exists,
in the navigate function I've got:
function navigate(str, what) {
if(what == null) {
what = document.documentElement;
} else {
what = document.getElementById(what);
}
what will become null because it's a not a valid Element at the moment of execution.
I've tried:
window.onLoad = naviate('main.php', 'content');
Which does nothing, same issue there..
Also tried putting the <script> block at the end without luck.
I can't use jQuery or anything so please keep it to standard Javascript, HTML and CSS.
Browsers in use: IE8, Chrome, FireFox.
Load index.php
Login to loginwindow
Load index.php
Upon completed load of index.php, read all elements including content
Update content with some AJAX data.
It works if
I login, load the page once with unsuccessful result and then refresh the page again.
And here's the reason why:
I use AJAX on the login window as well, it uses navigate() just as all my buttons and what not does. So the issue is that index.php gets loaded, with a login window, that login window updates the entire page with AJAX (javascript) which in turn, tries to call navigate() again from within the return data from the AJAX call...
The "inline" navigate() gets called!!!, it's just that it doesn't know all the elements because it's load via AJAX.
Try this :
window.onload = function(){
navigate('main.php', 'content');
}
According to my tests you can get div element by .getElementById even before the page is loaded.
Do not forget that the navigate function must be defined before it is called. So if you have your scripts at the end of document (which is correct), you must call the function after execution of theese scripts.
But anyway, you've assigned the .onload function wrongly. Do it like this:
window.onload = function(event) {
/*any script here*/
}
Or like this:
function load(event) {
/*any script here*/
}
window.onload =load;

Categories

Resources