How to add a javascript code to the page at runtime? - javascript

I have the below script and noscript javascript codes:
<script type="text/javascript" src="https://www.google.com/recaptcha/api/challenge?k=6LfWqtgSAAAAAP1KwYFYGt0wDeJFtxznmqyRH_Q5"> </script>
<noscript>
<iframe src="https://www.google.com/recaptcha/api/noscript?k=6LfWqtgSAAAAAP1KwYFYGt0wDeJFtxznmqyRH_Q5"
height="300" width="500" frameborder="0"></iframe>
<br>
<textarea name="recaptcha_challenge_field" rows="3" cols="40"> </textarea>
<input type="hidden" name="recaptcha_response_field" value="manual_challenge">
</noscript>
The above codes should be added to the page body only and only when a javascript variable is set from the server.
var shouldShow = true;
$document.ready(function() {
if (shouldShow) {
// add
} else {
// don't add
}
});
How would that possible to add those scripts at runtime?
Thanks,

You can use Page.RegisterStartupScript
if (shouldShow) {
Page.RegisterStartupScript...
}

You can do that like this:
var shouldShow = true;
$document.ready(function() {
if (shouldShow) {
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = 'https://www.google.com/recaptcha/api/challenge?k=6LfWqtgSAAAAAP1KwYFYGt0wDeJFtxznmqyRH_Q5';
document.body.appendChild(newScript);
} else { ... }
And you can freely ignore noscript. As it is shown only if there is no JS enabled, but in that case it will not be added anyway.
But why not simply place it into some asp:panel, for instance, and set its visibility to true/false depending on if it should be shown or not? If some asp.net element has elem.Visibility = false it is not sent to browser, the same as all its content.

Related

Javascript trouble in dynamically call another class in other js file

I'm trying to make a javascript function to call another .js file like this:
scriptCaller.js
function callScript(file){
var script = document.createElement('script');
script.id = file;
script.type = 'text/javascript';
script.async = true;
script.src = "script/"+file+".js";
document.getElementById('scriptSection').appendChild(script);
}
Then I create some class to be called by that script in other file:
divGenerator.js
function divGenerator(){
var self = this;
var div = document.createElement('div');
this.tag = function(){
return div;
}
/*and some other function to style the div*/
}
Then i make the main file to be executed:
main.js
function build(){
callScript('divGenerator');
}
function main(){
var test = new divGenerator();
/*execute some function to style the div*/
document.getElementById('htmlSection').appendChild(script);
}
All the three file will be called in a HTML files that will execute the main function:
myPage.html
<html>
<head>
<title>myPage</title>
</head>
<script src="scriptCaller.js"></script>
<script src="main.js"></script>
<body>
<div id="htmlSection"></div>
<div id="scriptSection"></div>
</body>
</html>
<script>build();</script>
<script>main();</script>
If I correct it should display the styled div, but what I got is an error that said:
TypeError: divGenerator is not a constructor[Learn More]
But, when I move the divGenerator() class to myPage.html it works fine. Any idea to solve this problem?
You need to add scriptCaller.js and divGenerator.js to your html script element.
<html>
<head>
<title>myPage</title>
</head>
<script src="scriptCaller.js"></script>
<script src="main.js"></script>
<script src="scriptCaller.js"></script>
<script src="divGenerator.js"></script>
<body>
<div id="htmlSection"></div>
<div id="scriptSection"></div>
</body>
</html>
<script>build();</script>
<script>main();</script>
You have couple of problems in your code. First of all, do not assign id to script element same as the "exported" global constructor name. You need to remember that anything with id attribute (and name) automatically gets exposed as global variable on window object. It means that divGenerator in your case is going to be reference to HTMLScriptElement, not a constructor function.
Second problem is related to timing, since you are loading script with async attribute. This is good, but you need to realise that in this case you can't expect that script will be loaded when you call main after build(). I would suggest to wrap script creation into promise:
function callScript(file){
return new Promise(function(resolve) {
var script = document.createElement('script');
script.id = 'script-' + file; // Note different id
script.async = true;
script.src = "script/" + file + ".js";
script.onload = resolve
document.getElementById('scriptSection').appendChild(script);
})
}
and use it like this:
<script>
build().then(function() {
main();
})
</script>

Pass URL parameters to script using Javascript include

I'm trying to create a javascript tracker that can be included on any page, that will pass the variables "ref" and "aff" from the URL to the PHP code that does the tracking.
This code works perfectly for my purposes on PHP pages:
<script type="text/javascript" src="//www.foo.com/reftracker.php?ref=<?= $_GET['ref'] ?>&aff=<?= $_GET['aff'] ?>">
</script>
<noscript>
<div style="display:inline;">
<img height="1" width="1" style="border-style:none;" alt="" src="//www.foo.com/reftracker.php?ref=<?= $_GET['ref'] ?>&aff=<?= $_GET['aff'] ?>"/>
</div>
</noscript>
The issue is that I also need to add the tracker to non-PHP pages, so I need a pure Javascript solution to pass those URL parameters into src attributes.
[EDIT]
For anyone interested, here is the solution I ended up with:
<script type="text/javascript">
function fooParamParse(val) {
var result = '', tmp = [];
location.search.substr(1).split("&").forEach(function (item) {
tmp = item.split("=");
if (tmp[0] === val) result = decodeURIComponent(tmp[1]);
});
return result;
}
var script = document.createElement('script');
document.getElementsByTagName('head')[0].appendChild(script);
script.src = "//www.foo.com/reftracker.php?ref="+fooParamParse('ref')+"&aff="+fooParamParse('aff')+"";
</script>
You will need a pure javascript solution for that. Read here on how to read the GET parameters from url in javascript
Then add the follwing js code
var script = document.createElement('script');
document.getElementsByTagName('head')[0].appendChild(script);
script.src = "//www.foo.com/reftracker.php?ref="+GET['ref']+"&aff="+ GET['aff']+"";
// assuming the GET parameters from javascript are stored in a hash GET

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>

How to modify the javascript code to receive input from the user?

I am struck with my language translation tool .
Here is the code that google translate API has .
I have to modify this code to receive input from the user in a text box and then identify the language it is typed in. Currently the code is picking up the values from id="sourceText" .
I need to put in a text box there to make it a simple dynamic tool . Please tell me what modifications should be made to add a text box and receive its input and detect the language ? Thanks...
<html>
<head>
<title>Translate API Example</title>
</head>
<body>
<div id="sourceText">Hello world</div>
<div id="translation"></div>
<script>
function translateText(response) {
document.getElementById("translation").innerHTML += "<br>" + response.data.translations[0].translatedText;
}
</script>
<script>
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
var sourceText = escape(document.getElementById("sourceText").innerHTML);
var source = 'https://www.googleapis.com/language/translate/v2/detect?key=INSERT-YOUR-KEY&source=en&target=de&callback=translateText&q=' + sourceText;
newScript.src = source;
// When we add this script to the head, the request is sent off.
document.getElementsByTagName('head')[0].appendChild(newScript);
</script>
</body>
</html>
Change
<div id="sourceText">Hello world</div>
to
<textarea id="sourceText">Hello World</textarea>
Also update this line:
var sourceText = escape(document.getElementById("sourceText").value);
<html>
<head>
<title>Translate API Example</title>
</head>
<body>
<textarea id="sourceText">Hello world</textarea>
<input type="button" value="Translate" onclick="submit()" />
<div id="translation"></div>
<script>
function translateText(response) {
document.getElementById("translation").innerHTML += "<br>" + response.data.translations[0].translatedText;
}
function submit() {
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
var sourceText = escape(document.getElementById("sourceText").innerHTML);
var source = 'https://www.googleapis.com/language/translate/v2/detect?key=INSERT-YOUR-KEY&source=en&target=de&callback=translateText&q=' + sourceText;
newScript.src = source;
// When we add this script to the head, the request is sent off.
document.getElementsByTagName('head')[0].appendChild(newScript);
}
</script>
</body>
</html>
How about changing
<div id='mySource'>
into
<textarea id='mySource'>
and put the code responsible for translation into function, and add a button "trasnalte", which onclick event would launch translating function?

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