I got a challenge trying to better understand how things work in this world. There are two html pages:
one.html
<html>
<script>
var ifrm = document.createElement("iframe");
var c = document.head;
ifrm.src = 'two.html';
(c = document.head || document.body) && c.appendChild(ifrm);
//ifrm.parentNode && ifrm.parentNode.removeChild(ifrm)
</script>
</html>
two.html
<html>
<script>
var newL = parent.document.createElement("img");
newL.src = 'http://qwerty.com';
parent.document.body.appendChild(newL);
</script>
</html>
I can control contents of two.html and I'm trying to create something in a parent, which would persist even after uncommenting the last line in the JS from one.html. As of now, the tag is successfully created but once I uncomment the line with removeChild(), it's gone. Can one explain me why, and if there is a way to complete the task under specified circumstances? Thanks in advance!
Related
I am automating a process wherein I have to login to website and download only the CSV files from the different types of files.
My jQuery code is getting executed in the console but not getting executed after integrating with HTML. Please find the jQuery code below :
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(window).on("load", function() {
$('.ibody tr').each(function(a, b) {
var count = 0;
var name = $('.cl', b).text();
if (name.indexOf(".CSV") !== -1 && name.indexOf("TAS") !== -1) {
var d = a - 9;
var hiddenIFrameID = 'hiddenDownloader' + count++;
var iframe = window.createElement('iframe');
iframe.id = hiddenIFrameID;
iframe.style.display = 'none';
window.body.appendChild(iframe);
iframe.src = "https://www.shipper-ml.com/viewReports.do?ctrl=reportListForDownload&action=DownloadReport¶m=" + d;
}
});
});
</script>
</head>
<body></body>
</html>
EDIT: I was, indeed, off-base with this. Didn't read your code carefully.
leaving this here for historical purposes...
I might be completely off-base with my assumptions here, and apologize in advance if this is the case. That said, it really looks like you are trying to load a page inside an IFrame and use jQuery outside of the IFrame to read data from inside the IFrame.
Long story short: you cannot use jQuery (or any javascript, or, indeed, ANYTHING AT ALL, if the browsers are working as they should) to manipulate or read content that is inside an IFrame, from outside the IFrame, if that IFrame has a src tag.
You can only manipulate / read from iframe you have built from scratch by yourself. This is by design, and for an important security reason. If you want to use IFrame to display a page, you are severely restricted to only show the page to user as-is.
If my assumption was correct, you need to either:
Get your JavaScript embedded (nicely) into the page you are now loading in your IFrame or
Use an AJAX call to get the contents of that page into your current page's memory context. This will probably mean jumping through some hoops if you really want to use jQuery to find all the elements you want.
...or, you may be able to create an empty IFrame, put the content you got from the AJAX call into that IFrame along with your Javascript, and get it to work. maybe. Not sure about this one.
can you please try with this? replace your window.createElement with document.createElement .
$(document).ready(function() {
$('.ibody tr').each(function(a, b) {
var count = 0;
var name = $('.cl', b).text();
if (name.indexOf(".CSV") !== -1 && name.indexOf("TAS") !== -1) {
var d = a - 9;
var hiddenIFrameID = 'hiddenDownloader' + count++;
var iframe = document.createElement('iframe');
iframe.id = hiddenIFrameID;
iframe.style.display = 'none';
document.body.appendChild(iframe);
iframe.src = "https://www.shipper-ml.com/viewReports.do?ctrl=reportListForDownload&action=DownloadReport¶m=" + d;
}
});
})
I have an iframe which needs to copy a script to the parent and execute a function in the parent:
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<script id="myscript">
function foo() { alert('foo'); }
</script>
<script>
(function () {
var script = document.getElementById('myscript');
parent.document.head.appendChild(script);
// call function in parent
parent.foo();
})();
</script>
</body>
</html>
I get undefined is not a function. Why is that function not defined in the parent?
Bear in mind that you will be subject to cross-origin security and other inter-frame restrictions, which shouldn't be an issue if you host both frames from the same domain, but will block this pretty effectively otherwise.
Getting an element from the child frame and appending it to the parent probably won't work, and is definitely overly complex. I would suggest creating a new script element on the parent and simply copying the content. Something like:
(function () {
var pdoc = parent.document;
var dest = pdoc.head;
var text = document.getElementById("myscript").textContent;
var pscr = pdoc.createElement("script");
pscr.textContent = text;
dest.appendChild(pscr);
parent.foo();
})();
This is fairly difficult to make a good example for, as JSFiddle and the like serve their frames from different origins, so I haven't tested it thoroughly. Getting the script content this way definitely works, and creating the element certainly should. The closest I could come while testing was to rename the function and use the current frame:
(function() {
var pdoc = self.document;
var dest = pdoc.head;
var text = document.getElementById("myscript").textContent.replace("foo", "bar");
var pscr = pdoc.createElement("script");
pscr.textContent = text;
dest.appendChild(pscr);
self.bar();
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If you want this to be a more portable solution, you may also look into using the onMessage handler in the script and firing a message from the child (message-passing is somewhat more complex, but often more maintainable, than inter-frame calls).
The question says it all. How to update the "src" of script tag using jQuery.
Let say, I have a script,
<script id="somescript" type="text/javascript" src=""></script>
So when I a click on a button, the src of the script must be added. Like,
<script id="somescript" type="text/javascript" src="linktoscript.js"></script>
I am doing it with a click handler like this, using the following code.
$("#somescript").attr("src","linktoscript.js");
It actually updates the src but when I check it via firebug, it tells me to refresh the page to get the script working.
Research:
After some research, I've found $.get() of jQuery would do the job and yes, it loads the script. But it is not getting my job done.
The Actual Problem:
I am trying to load Google's conversion code using Ajax on successful form submission.
Here is the part of the Ajax script that should work for the Google's conversion code.
if (res == "yes") {
$('#success').fadeIn().delay(5000).fadeOut();
$('#regform')[0].reset();
window.location.href = '#';
/* <![CDATA[ */
var google_conversion_id = xxxxxxxxx;
var google_conversion_language = "en";
var google_conversion_format = "2";
var google_conversion_color = "ffffff";
var google_conversion_label = "CiaXCOXjzlcQy__EyQM";
var google_remarketing_only = false;
/* ]]> */
$.getScript("http://www.googleadservices.com/pagead/conversion.js");
}
It loads the conversion script but when I check it from firebug, all the values of the conversion variables are null.
So I am giving it a try by putting all of the conversion code into the html file and then load the conversion script like,
<script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = xxxxxxxxx;
var google_conversion_language = "en";
var google_conversion_format = "2";
var google_conversion_color = "ffffff";
var google_conversion_label = "CiaXCOXjzlcQy__EyQM";
var google_remarketing_only = false;
/* ]]> */
</script>
<script type="text/javascript" src="#"></script> <!--Update this src-->
<noscript>
<div style="display:inline">
<img height="1" width="1" style="border-style:none;" alt="" src="#" />
</div>
</noscript>
Any Help?
Link:
Here is the link to the live site : Link
Update:
This is what I get. In the firebug's script panel, after form submission,
It would appear that the Google conversion script relies on google_conversion_id, google_conversion_language, etc. to be available as global variables. Presuming that the code you have there is executing inside a function (which would make sense if this is inside an event), the code you have there will not work because the variables will be local to the function they are in, and the google code will have no way to get at them.
There are two things you can do.
One is to define those variables in the global scope ahead of time, i.e. do this:
<script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = xxxxxxxxx;
var google_conversion_language = "en";
var google_conversion_format = "2";
...
</script>
(you can also put these in an external script file and load that file when the page loads:
If you do that, you can load the google conversion script whenever you want, and it will be able to access those variables:
$.getScript("http://www.googleadservices.com/pagead/conversion.js");
The other option is to assign your variables to the window object right before you load the script, which is equivalent to putting them in the global scope:
if (res == "yes") {
$('#success').fadeIn().delay(5000).fadeOut();
$('#regform')[0].reset();
window.location.href = '#';
window.google_conversion_id = xxxxxxxxx;
window.google_conversion_language = "en";
window.google_conversion_format = "2";
window.google_conversion_color = "ffffff";
window.google_conversion_label = "CiaXCOXjzlcQy__EyQM";
window.google_remarketing_only = false;
$.getScript("http://www.googleadservices.com/pagead/conversion.js");
}
Note: regarding the issue that this question was originally about, you can't load a script by changing the src attribute of an existing script element:
http://jsfiddle.net/5vf6b924/
Once a script element has loaded whatever is indicated by the src (even if it's #), it is essentially "used up" and won't load anything else.
What you can do is to create a new script element and add it to the DOM:
http://jsfiddle.net/ydu52cn1/
That should succeed in loading the script (asynchronously).
As you've found, jQuery also provides the $.getScript convenience method for this.
At the end, the following did the job for me. Thanks to JLRishe and A. Wolff for their support.
In my previous code, there were two problems.
I was not inserting the "img" element along with other conversion code. (Silly mistake but I was working with conversion code for the first time. So please pardon me).
Inserting src of the "img" tag in the default format would give error. The default & would render Invalid URL encode error upon AJAX response. Thanks for Tag Assitant. Rather than using &, use & directly like this.
www.googleadservices.com/pagead/conversion/xxxxxxxxx/?label=CiaXCOXjzlcQy__EyQM&guid=ONscript=0
Here is what finally worked for me.
if (res == "yes") {
$('#success').fadeIn().delay(5000).fadeOut();
$('#regform')[0].reset();
<!-- Google Code for Lead Conversion Page -->
/* <![CDATA[ */
window.google_conversion_id = xxxxxxxxx;
window.google_conversion_language = "en";
window.google_conversion_format = "2";
window.google_conversion_color = "ffffff";
window.google_conversion_label = "CiaXCOXjzlcQy__EyQM";
window.google_remarketing_only = false;
/* ]]> */
$.getScript("//www.googleadservices.com/pagead/conversion.js");
window.scriptTag2 = document.createElement('noscript');
window.imgTag = document.createElement('img');
imgTag.height = 1;
imgTag.width = 1;
imgTag.border = 0;
imgTag.src = "//www.googleadservices.com/pagead/conversion/xxxxxxxxx/?label=CiaXCOXjzlcQy__EyQM&guid=ONscript=0";
}
I hope it will help the someone else with the same problem.
Thank you.
You could append the script tag to the DOM
if (yourCondition === true) {
$('head')
.append($('<script id="somescript" type="text/javascript" src="linktoscript.js"></script>'));
}
The script is loaded at the moment it is appended, that way you have total control of when it is loaded.
We are using the Ning platform, and in order to add a new container DIV underneath the blog content (but before the comment section), we added the following before the body tag:
<script type="text/javascript">
if (typeof(x$) != 'undefined') {
x$("DIV.xg_module.xg_blog.xg_blog_detail.xg_blog_mypage.xg_module_with_dialog").after('<div>CONTENT GOES HERE </div>');
}
else{
}
</script>
However, then the content we need to load is javascript from an affiliate program, who sent us this code to add into that div:
<div style="width:750px;">
<div style="border-bottom:1px solid #FFFFFF;color:#FFFFFF;font-family:Arial,Helvetica,sans-serif;font-size:22px;font-weight:bolder;margin-bottom:10px;padding-bottom:2px;text-transform:uppercase;">From Around the Web</div>
<script type='text/javascript'>
var _CI = _CI || {};
(function() {
var script = document.createElement('script');
ref = document.getElementsByTagName('script')[0];
_CI.counter = (_CI.counter) ? _CI.counter + 1 : 1;
document.write('<div id="_CI_widget_');
document.write(_CI.counter+'"></div>');
script.type = 'text/javascript';
script.src = 'http://widget.crowdignite.com/widgets/29949?_ci_wid=_CI_widget_'+_CI.counter;
script.async = true;
ref.parentNode.insertBefore(script, ref);
})(); </script>
</div>
And obviously, that does not work.
THE QUESTION: is there a better way to do this? Is it just a matter of all the conflicting 's and "s? Is there an easier way to format this or output it? Is it failing because it's simply not loading the javascript after the JQuery has already run post-page load? I have been trying different things and none seem to work and my eyes are ready to pop out of their sockets because I know there's something stupid I'm missing, so I thought I'd get some more eyes on it.
Thanks for any help/ideas/suggestions.
Try appending your new script element to the head element on your page. Most dynamic script loaders do this.
See Ways to add javascript files dynamically in a page for an example.
I have an odd problem. the question is not so much about specifics of the code, more to the general approach.
scenario: a website has a "welcome screen". The welcome element is an HTML5 EDGE animation (its not a small file ;) ) Using client side detection, we will check if cookies are enabled. if cookies are enabled, we check for a cookie['loader_shown']. if we dont see this cookie, we want to use JS to show a full screen overlay div half opaque. inside this div, we then want to use AJAX to load in the loading element html - at the moment this is defined in a seperate file, and of course refences other files in the EDGE file package...
Any suggestions on how best to approach this. it is important the HTML5 EDGE element is only loaded from the server once the welcome detection has oipened the first overlay div....
oh, the EDGE element must remain transparent!
solved. the best approach is to dynamically load the js files once the cookies have been checked:
sources in comments
<!DOCTYPE HTML>
<html lang="en">
<head>
<script type="text/javascript">
var cookiesEnabled = are_cookies_enabled();
function are_cookies_enabled() // http://sveinbjorn.org/cookiecheck
{
var cookieEnabled = (navigator.cookieEnabled) ? true : false;
if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled)
{
document.cookie="testcookie";
cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false;
}
return (cookieEnabled);
}
// http://www.hunlock.com/blogs/Howto_Dynamically_Insert_Javascript_And_CSS
if(cookiesEnabled == true)
{
var headID = document.getElementsByTagName("head")[0];
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.charset = 'utf-8';
//newScript.onload=scriptLoaded; // If you're loading an external javascript and you need to know when the script has loaded you can simply use .onload=yourfunction; to set up the onload handler. Here's an example.
newScript.src = '_loader/head3_C_213_no_preloader_edgePreload.js';
headID.appendChild(newScript);
}
</script>
<style>
.edgeLoad-EDGE-614773 {
display:none;
}
</style>
</head>
<body style="margin:0;padding:0;">
<h1>test</h1>
<div id="Stage" class="EDGE-614773">
</div>
</body>
</html>
never really thought about JS loading itself from script like that...... Oh the possibilities!