javascript script is hidden in source view - javascript

Why don't the script tags and content appear inside a div tag for example.
I have the following code:
<div>
<!-- BEGIN: YTV Syndicate script -->
<!-- Edit Section-->
<script type="text/javascript">
alert('hello!'); //check if scripts actually works
var YTVSYND = {}
YTVSYND.key = 'xxx';
YTVSYND.template = {}
YTVSYND.template.name = 'ytv'
YTVSYND.template.size = 'size300x250'
YTVSYND.soc = '<%= Model.Code %>';
YTVSYND.type = 'career';
</script>
<!-- END: EDIT -->
<!-- === DO NOT EDIT BELOW=== -->
<script type="text/javascript">
var ytvSyndUrl = (location.protocol == 'https:') ? 'https://' : 'http://';
ytvSyndUrl += 'syncdn.youniversitytv.com/synapi/embed/ytv-embed-api.js';
ytvSyndUrl = "/Scripts/ytv-embed-api.js"
var str = "<scr" + "ipt type='text/javascript' src='" + ytvSyndUrl + "'>";
str += "<";
str += "\/scr" + "ipt>";
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = ytvSyndUrl;
$("#fgm").html(str)
</script>
<!-- EOF: YTV Syndicate script -->
</div>
It executes just but when I check the source it only shows the comments
<!-- BEGIN: YTV Syndicate script -->
<!-- Edit Section-->
<!-- END: EDIT -->
<!-- === DO NOT EDIT BELOW=== -->
<!-- EOF: YTV Syndicate script -->
and no sign of the script tags and the actual script .
Note: this is inside a jquery modal, i have the same script inside a normal page and it shows up in the source view.
1st
2nd

When you load some HTML content into the DOM dynamically with jQuery, it strips out the <script> tags completely. Under most circumstances it evaluates them (with "eval()" which is more-or-less what the browser would do), but they don't remain available in the DOM.
You can see the code in the jQuery source starting around this point.
edit — note that I'm assuming that you're adding some HTML dynamically. If you were not doing that, then the <script> tags would be in the DOM, and you would be able to see them in Firebug, etc.

View source is not your solution
view dom is you solution
use web developer of firebug

Related

How can I use Google Analytics code in React JS app?

I want to use below Google Analytics code in my react JS app in the script tag.
When I put the below code in Helmet I showing a syntax error?
How Can I use it?
<script>
(function (w, d, s, l, i) {
w[l] = w[l] || [];
w[l].push({
"gtm.start": new Date().getTime(),
event: "gtm.js",
});
var f = d.getElementsByTagName(s)[0],
j = d.createElement(s),
dl = l != "dataLayer" ? "&l=" + l : "";
j.async = true;
j.src = "https://www.googletagmanager.com/gtm.js?id=" + i + dl;
f.parentNode.insertBefore(j, f);
})(window, document, "script", "dataLayer", "GTM-Code");
</script>
<!-- End Google Tag Manager -->
<!-- Makes it possible to add onclick attribute to buttons and such -->
<script>
window.onload = function () {
var anchors = document.getElementsByTagName("*");
for (var i = 0; i < anchors.length; i++) {
var anchor = anchors[i];
anchor.onclick = function () {
code = this.getAttribute("whenClicked");
eval(code);
};
}
};
</script>
Simply do below two steps, Copy the code below and paste it onto every page of your test environment.
Paste this code as high in the head of the page as possible:
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;
f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXX');</script>
<!-- End Google Tag Manager -->
Additionally, paste this code immediately after the opening body tag:
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
As per the provided source code, you didn't add noscript tag after the body tag.
Please provide exact error you are having to get more understanding of
the issue.
You could try using a 3rd party library such as React GA that handles script injection for you.

How to add dataLayer object and Google Tag Manager container snippet from body tag

I have a few dynamic values which I get inside the body tag only. Now when I try to push those values using dataLayer object using 'script' tag and prepend it to the head section, it does not work.
Here is the code -
<script type="text/javascript">
var head = document.getElementsByTagName('head')[0];
var JS = document.createElement('script');
<!-- Google Tag Manager -->
var tagManagerSnippet = '(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({"gtm.start":\n' +
'new Date().getTime(),event:"gtm.js"});var f=d.getElementsByTagName(s)[0],\n' +
'j=d.createElement(s),dl=l!="dataLayer"?"&l="+l:"";j.async=false;j.src=\n' +
'"https://www.googletagmanager.com/gtm.js?id="+i+dl;f.parentNode.insertBefore(j,f);\n' +
'})(window,document,"script","dataLayer","GTM-XXXXXXXX");\n';
<!-- End Google Tag Manager -->
JS.text = tagManagerSnippet;
head.prepend(JS);
var code = 'dataLayer = [];\n' +
'dataLayer.push({"eventLabel" : "Interested in Science"});\n' +
'dataLayer.push({"eventLabel" : "Interested in IT"});\n';
JS.text = code;
head.prepend(JS);
</script>
I can see that the above code properly executes and append the JS in the head section. However, the Tag does not fire. And when I simply put the above code in the head section (not on the fly) it runs as expected.

Summernote text editor not working in simple bootstrap page where html is generated

I added Summernote (a text editor for bootstrap) to a small page I am testing a form generator on. I cannot seem to be able to get the editor in my page at all, even if the examples are simple.
See this simplified jsfiddle I made that works and only has 2 lines.
This is my index.html file:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css">
<script src="https://code.jquery.com/jquery-2.2.3.min.js" defer></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script src="js/bootstrap-checkbox.min.js" defer></script>
<script src="js/bootstrap-filestyle.min.js" defer></script>
<link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.1/summernote.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.1/summernote.js"></script>
<script src="js/myJavaScript.js"></script>
</head>
<body onload="addAllElements()">
<br/>
<div class="row" id="mainRow">
</div>
</body>
</html>
And this is my javascript file:
//This function should read a json file and produce the right form
function addAllElements() {
//A test for generated forms (from objects)
for (var i = 0; i < 3; i++) {
addElement({
label: "Some rich text editing :",
tag: "richEditor",
});
}
//We add the styling for checkboxes, file inputs and rich editors
$(':checkbox').checkboxpicker();
$(":file").filestyle({ buttonText: "File", buttonName: "btn-primary", placeholder: "No file" });
$('#richEditor').summernote();
}
//This function add a single element to the form
function addElement() {
//We create the group div (the whole element div)
var newDiv = document.createElement("div");
if(arguments[0].tag !== "richEditor"){
newDiv.className = "form-group col-xs-12 col-sm-6 col-lg-4 col-xl-3";
}else{
newDiv.className = "form-group col-xs-12 col-sm-12 col-lg-12 col-xl-12";
}
//We create and add the label to the div
var newLabel = document.createElement("label");
if(arguments[0].tag == "richEditor"){
newLabel.className = "col-xs-6 col-sm-5 control-label";
}else{
newLabel.className = "col-xs-6 col-sm-5 control-label";
}
newLabel.innerHTML = arguments[0].label;
newDiv.appendChild(newLabel);
//We create and add the input to the div
var inputDiv = document.createElement("div");
if(arguments[0].tag == "richEditor"){
inputDiv.className = "col-xs-6 col-sm-7";
}else{
inputDiv.className = "col-xs-6 col-sm-7";
}
newDiv.appendChild(inputDiv);
switch (arguments[0].tag) {
case "richEditor":
var newInput = document.createElement("div");
newInput.className = "form-control";
newInput.id = "richEditor";
inputDiv.appendChild(newInput);
break;
default:
}
var mainRow = document.getElementById("mainRow");
mainRow.appendChild(newDiv);
}
Would you have an idea on how to correct my code so the editor would actually load in the space I am giving it?
Bootstrap plugins depend on jQuery; they'll fail if it doesn't load first:
Plugin dependencies
Some plugins and CSS components depend on other plugins. If you include plugins individually, make sure to check for these dependencies in the docs. Also note that all plugins depend on jQuery (this means jQuery must be included before the plugin files). Consult our bower.json to see which versions of jQuery are supported.
The defer attribute in your jQuery script loading tag is causing it to load after you call addAllElements in your onload event.
defer
This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed. Since this feature hasn't yet been implemented by all other major browsers, authors should not assume that the script’s execution will actually be deferred. The defer attribute shouldn't be used on scripts that don't have the src attribute. Since Gecko 1.9.2, the defer attribute is ignored on scripts that don't have the src attribute. However, in Gecko 1.9.1 even inline scripts are deferred if the defer attribute is set.

Javascript appendChild(script) works only one time

I'm trying to create two separate HTML documents: main.html and sufler.html. Idea is to control sufler.html page from main.html . So far I succeeded to write text and change it's font style. But font style changes only ONE time...
I need it to be able to change many times, can't understand what is going on,
because, as I understanding, every time I calling function writing(), I'm clearing all new document's content with newDoc.body.innerHTML = ''... but it seems that not... although text is changing every time.
main.html
<html>
<head>
<script type="text/javascript">
var HTMLstringPage1 = '<!DOCTYPE html><html><head><link href="stilius.css" rel="stylesheet" type="text/css" /></head><body>',
HTMLstringPage2 = '</body></html>',
HTMLstringDiv1 = '<div id="sufler"><div id="mov"><p id="flip">',
HTMLstringDiv2 = '</p></div></div>';
//NEW WINDOW OPEN--------------------------------------------------------------------------------------------------------
var newWindow = window.open('suffler.html','_blank','toolbar=no, scrollbars=no, resizable=no, height=615,width=815');
var newDoc = newWindow.document;
newDoc.write(HTMLstringPage1,HTMLstringDiv1+'Text'+HTMLstringDiv2,HTMLstringPage2);
var script = newDoc.createElement("script");
script.type = "text/javascript";
//=======================================================================================================================
//WRITING----------------------------------------------------------------------------------------------------------------
function writing(){
newText = document.getElementById("sel-1").value.replace(/\n/gi, "</br>");
fontas= document.getElementById("textFont").value;
size= document.getElementById("textSyze").value;
stylas= document.getElementById("textStyle").value;
syntax= document.getElementById("textSyntax").value;
newDoc.body.innerHTML = '';//clears old text (should clear old scripts and functions too)
newDoc.write(HTMLstringPage1,HTMLstringDiv1,newText,HTMLstringDiv2,HTMLstringPage2);//writes new text (and new scripts and functions)
var text = newDoc.createTextNode('document.getElementById("flip").style.font="'+stylas+' '+syntax+' '+size+'px '+fontas+'";');
script.appendChild(text);
newDoc.getElementsByTagName("body")[0].appendChild(script);
}
//=======================================================================================================================
</script>
</head>
<body>
<button type="button" style="background-color: #F5FF25;" onclick="writing()">Apply text</button>
</body>
</html>
Any one node can only be added to the document once. You only define script once but trying to add it to the DOM multiple times. Put the var script = ... line inside writing().

jquery to run in iframe when created on the fly

I am trying to first create an iframe and then inject into it jQuery library and then have an alert to say that jQuery has loaded.
The jQuery library is being inserted into the iframe head as expected and the alert on jQuery load into the body.
The problem is, it does not show the alert and instead says jQuery is not defined.
Can anyone suggest anything?
Here is the code
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<title>iFrame Test</title>
</head>
<body>
<script>
var insertScript = function(src){
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = false;
script.src = src;
$('iframe').contents().find('head')[0].appendChild(script);
}
var insertScriptContent = function(code){
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = false;
script.innerHTML = code;
$('iframe').contents().find('body')[0].appendChild(script);
}
$(function(){
$('iframe').load(function(){
var contents = $('iframe').contents();
insertScript('https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js');
insertScriptContent('jQuery(function(){ alert("loaded"); });');
});
});
</script>
<div class="output">
<iframe></iframe>
</div>
</body>
</html>
You're loading jQuery asynchronously (despite the script.async=false) and then loading your alert script immediately after that. jQuery is not yet loaded when that script runs, so you get the undefined jQuery reference.
As a quick fix, I added a setInterval() that waits until jQuery is defined. I also made these other changes:
Removed the script.async = false; both places because it doesn't do any good.
Removed the $('iframe').load() wrapper. When I tested your code, the callback function in that wrapper never gets called at all. That's not surprising since nothing is being loaded into the iframe at that point.
Changed the two places where you use document.createElement() to use the iframe document (called iframedoc in my version) instead. It works OK using document, but I'm a bit more comfortable creating those scripts under the document they will be loaded into.
Changed two instances of ...find(something)[0].appendChild(); to the simpler ...find(something).append();.
Here's the working code:
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript">
</script>
<title>iFrame Test</title>
</head>
<body>
<script type="text/javascript">
$(function() {
var $contents = $('iframe').contents();
var iframedoc = $contents[0];
var insertScript = function(src) {
var script = iframedoc.createElement('script');
script.type = 'text/javascript';
script.src = src;
$('iframe').contents().find('head').append(script);
}
var insertScriptContent = function(code) {
var script = iframedoc.createElement('script');
script.type = 'text/javascript';
script.innerHTML = code;
$('iframe').contents().find('body').append(script);
}
insertScript('https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js');
insertScriptContent(
'var timer = setInterval( function() {' +
'if( typeof jQuery == "undefined" ) return;' +
'clearInterval( timer );' +
'jQuery(function(){ alert("loaded"); });' +
'}, 50 )'
);
});
</script>
<div class="output">
<iframe></iframe>
</div>
</body>
</html>
That was good for a first pass, but there's a simpler way to do it. I tried replacing the two script functions with jQuery code, so here is another working version:
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript">
</script>
<title>iFrame Test</title>
</head>
<body>
<script type="text/javascript">
$(function() {
var $contents = $('iframe').contents();
$contents.find('head').append(
'<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"><\/script>'
);
$contents.find('body').append(
'<script>' +
'jQuery(function(){ alert("loaded"); });' +
'<\/script>'
);
});
</script>
<div class="output">
<iframe></iframe>
</div>
</body>
</html>
Oddly enough, this one works OK without the setInterval() timer, so I took that code out. I'm not sure exactly why this works - which is not a comforting feeling - but it does seem to be consistent in the browsers I tested it in.
And finally, here is a non-working experiment. In the past I've used document.write() targeting an iframe to good effect. So I thought I would try that:
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript">
</script>
<title>iFrame Test</title>
</head>
<body>
<script type="text/javascript">
$(function() {
var $contents = $('iframe').contents();
var iframedoc = $contents[0];
iframedoc.write(
'<!doctype html>',
'<html>',
'<head>',
'<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.js"><\/script>',
'</head>',
'<body>',
'<script>',
'debugger;',
'jQuery( function(){ alert("loaded"); } );',
'<\/script>',
'</body>',
'</html>'
);
});
</script>
<div class="output">
<iframe></iframe>
</div>
</body>
</html>
This version does load jQuery and the inline script into the iframe, and it executes the jQuery() call in the inline script. But it never calls the callback function with the alert() in it. This actually relates to something I'm working on, so I'll probably take another look at it tomorrow, but in the meantime I left the experimental code in case you're curious. I changed it to use the uncompressed jQuery inside the iframe for easy debugging, and left a debugger; statement in there.

Categories

Resources