I'm trying to generate a JS script using JS sounds tricky. But the function inside the generated script comes to form and I try to call, it says undefined I'm giving a minimalistic example of my code. I don't know why it's happening maybe function defining on appending or changing the inner html does not work. If you can figure it out that how I can solve this problem, please tell me it'll help out a lot. Thanks! here is the example code.
<body>
<script>
let b = '<script>function amb(){console.log("hello")}' + '<' + '/' + 'script>'
document.body.innerHTML = b
</script>
<div id="a">
<button onclick="amb()"> amb</button>
</div>
</body>
That is probably because it is not loaded if you just add it afterwards. Nevertheless generating code with code should be avoided! If anywhere input data is used it is that vulnerability. Also it is bad code and hard to understand.
You should overthink your concept and maybe try to explain what you want to achieve and search for in the internet. Or maybe we can here give you a suggestion.
With the suggestion from #Lk77
A solution I would NOT recommend! could look like:
<div>
<button> amb</button>
</div>
let s = document.createElement('script');
s.text = 'function amb(){ console.log("hello"); }'
document.body.appendChild(s);
document
.querySelector('button')
.addEventListener('click', amb);
regarding your answer in the comments
I'm making a website which is used to generate tables it requires a form but I'm too lazy to write hundreds lines of html so i used js but someone has told me that the code generated afterwards is not loaded. I don't know how can i load the generated code
try to think simple... instead of generating code to generate you sth. use js to generate html that's the purpose of js. 100% sure you don't need to code code that generates code. You can create a website that is 99% powered by javascript that kind is called webapp. https://angular.io/start is one of many frameworks to achieve that. And none of them generates code by code.
You can't use innerHTML, you will need to append to the body :
var s = document.createElement( 'script' );
s.text = 'alert("test")'
document.body.appendChild( s );
but the real question is why you want to do that
Related
I'm trying to get the hang of ClientDependency Framework.
https://github.com/Shazwazza/ClientDependency
I use it in an Umbraco website.
I'm having a problem with some custom javascript (not in a file) that I want to run.
I want to run a function (which is in "functions.js"), but with a different parameter per page.
So, I add the following to my template:
Html.RequireJs("~/scripts/functions.js", 1);
And on my masterpage before the -tag I've added:
#Html.RenderJsHere()
But where do I place my function-call? I can't just add it to my template, because "functions.js" isn't loaded yet (it's at the bottom of my masterpage).
I've thought about creating a js-file for each call and add them to the Html.RequireJs(...) but that isn't a great solution.
Is there a way to add inline-script to the list of "JS-to-render" ?
edit:
I was just trying to get it to work using RenderSection(), but that doesn't seem to work when the section is defined on a macro?
edit:
I don't have the code here at the moment I'm typing this, but the idea is like this:
functions.js
function WriteToConsole(input) {
console.log('Log', input);
}
template1.cshtml
#{Html.RequireJs("functions.js");}
<script>
WriteToConsole("This is from template 1");
</script>
template2.cshtml
#{Html.RequireJs("functions.js");}
<script>
WriteToConsole("This is from template 2");
</script>
master.cshtml
<body>
#RenderBody()
#Html.RenderJsHere()
</body>
Just to give an idea of what I'm trying to do.
As you can imagine, the <script> part on my template is now being called before functions.js is included. And this results in an error.
Or am I handling this whole thing wrong?
Are you trying to alter the script call in: Html.RequireJs("~/scripts/functions.js", 1); ?
So something like Html.RequireJs("~/scripts/functions.js?myparam=xyz", 1); Is this what you are trying to achieve but having the url be dynamic?
If so you could do something like this :
//perhaps have some logic above to determine what the query should be and concatenate it to the string like so.
string query = "?myparam=xyz";
string scriptcall = "~/scripts/functions.js"+query ;
Html.RequireJs(scriptcall, 1);
Could you provide more code so we can see what you are trying to do? Maybe list in steps on how it should work?
HTML elements with a unique custom type attribute are ignored by the browser. Sometimes these are used by template engines. How do I define what happens when such a script element is loaded/created? (either while loading the page or when inserted dynamically)
In other words, does an onCreateElement event of some sorts exist in the DOM?
I could quite easily iterate through all script elements with attribute type=text/mycustomtype when the DOM loads using for instance the querySelector and then parse them with a function. This however does not work when a new script element is created and appended programatically. Is this currently possible?
var d = document.createElement('script')
d.setAttribute('type', 'text/mycustomtype')
d.innerHTML = 'define foo = 1;' // some code in some custom language
document.body.appendChild(d)
In this case, nothing will happen because the browser will ignore this unknown type. Can I somehow define a handler function for this? Thanks in advance.
I recently saw python script running in a browser using brython. View source and I see:
<script type="text/python3">
from interpreter import Interpreter
# open REPL in textarea with id "code"
Interpreter("code")
</script>
I wanted to know how this is possible. I googled for the answer, and found the dreaded stackoverflow question that's exactly what I want - with no answers.
I found a good answer in: Everything I Know About The Script Tag. It's exactly as you predicted when you say iterate through all script elements.
Their example looks like this:
<script type="text/emerald">
make a social network
but for cats
</script>
<script>
var codez = document.querySelectorAll('script[type="text/emerald"]');
for (var i=0; i < codez.length; i++)
runEmeraldCode(codez[i].innerHTML);
</script>
I'm turning here as a last resort. I've scoured google and I'm having troubles coming to a solution. I have a form with a textarea element that allows you to type html in the area and it will render the HTML markup live as you type if you have the preview mode active. Not too different from the way StackOverflow shows the preview below a new post.
However, I have recently discovered that my functionality has a vulnerability. All I got to do is type something like:
</textarea>
<script>alert("Hello World!");</script>
<textarea style="display: none;">
And not only does this run from within the textarea live, if you save the form and reload said data on a different page this code still executes within the textarea on said different page but unbeknownst to the user; to them all the see is a textarea (if there is no alert obviously).
I found this post; Live preview of textarea input with javascript html, and attempted to refactor my JS to the accepted answer there, because I noticed I couldn't write a script tag in the JSFiddle example, though maybe that's some JSFiddle blocking that behaviour, but I couldn't get it working within my JS file.
These few lines is what I use to live render HTML markup:
$(".main").on("keyup", "#actualTextArea", function () {
$('#previewTextArea').html($('#actualTextArea').val());
});
$(".main").on("keydown", "#actualTextArea", function () {
$('#previewTextArea').html($('#actualTextArea').val());
});
Is there a way this can be refactored so it's safe? My only idea at the moment is to wipe the live preview and use a toggle on/off and encode it, but I really think this is a cool feature and would like to keep it live instead of toggle. Is there a way to "live encode" it or escape certain tags or something?
In order to sanitise your text area preview simply replace all the < and > with their html character code equivalents:
function showPreview()
{
var value = $('#writer').val().trim();
value = value.replace("<", "<");
value = value.replace(">", ">");
$('#preview').html(value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="writer" onInput="showPreview();">
</textarea>
<br/>
<hr/>
<div id="preview">
</div>
Edit: Actually, I think this solution is a little cleaner, and makes the below code unnecessary. In the velocity page all that is needed is to take advantage of the Spring framework. So I replace the textarea with this like so:
#springBindEscaped("myJavaObj.textAreaText" true)
<textarea id="actualTextArea" name="${status.expression}" class="myClass" rows="10" cols="120">$!status.value</textarea>
This paired with some backend Java validation and it ends up being a much cleaner solution.
But if you want a non-spring/ velocity solution, then this below works just fine
I cobbled together a quick fix as my main purpose is to eliminate the ability for others to execute scripts easily. It's not ideal, and I"m not claiming it to be the best answer, so if someone finds a better solution, please do share. I created a "sanitize" function like so:
function sanitize(text){
var sanitized = text.replace("<script>", "");
sanitized = sanitized.replace("</script>", "");
return sanitized;
}
Then the previous two event handlers now look like:
$(".main").on("keyup", "#actualTextArea", function () {
var textAreaMarkup = $('#actualTextArea').val();
var sanitizedMarkup = sanitize(textAreaMarkup );
$('#actualTextArea').val(sanitizedMarkup);
$('#previewTextArea').html(sanitizedMarkup);
});
// This one can remain unchanged and infact needs to be
// If it's the same as above it will wipe the text area
// on a highlight-backspace
$(".main").on("keydown", "#actualTextArea", function () {
$('#previewTextArea').html($('#actualTextArea').val());
});
Along with Java side sanitation to prevent anything harmful being stored in the DB, this serves my purpose, but I'm very open to a better solution if it exists.
Good day! Newbie here. I just want to know if it's possible to change the whole content of an html using javascript? I got some codes here. (not mine but whoever did this, thank you so much!) I don't know where to put/insert all the codes of the new layout like when you click a button then the whole content will change. Thank you very much for helping me.
<script language="Javascript">
<!--
var newContent='<html><head><script language="Javascript">function Hi()</script></head><body onload="Hi();"><p id="p">hello</p></body></html>';
function ReplaceContent(NC) {
document.write(NC);
document.close();
}
function Hi() {
ReplaceContent(newContent);
}
-->
</script>
The easiest way to do this is with jQuery.
function insertHtml()
{
var newHtml = '<div><span>Hello World</span></div>';
$('body').html(newHtml);
}
Something like that will replace the entire contents of body with newHtml. You can also do this with pure javascript using the .innerHtml property but jQuery has many advantages.
EDIT: If you want to add something to the DOM rather than replacing the entire thing, use
$('body').append(newHtml)
instead. This will add the content to the end of the body. This is very often used for things like adding rows to a table.
Yes it is possible but this code is not valid unless you remove the comment tags however don't use the document.write() after page load unless you want to overwrite everything in page including the script
What I want to do is pretty simple. Above my blog I want to have a text paragraph with an explanation of the site. However I do not want it to be at the top of every page on the site ONLY the index page. My host has a very restrictive format. I've already asked them for help and it isn't possible with their editor. I cannot edit all of the html but I can change some. Javascript seems to be allowed so I have been trying things like:
<SCRIPT LANGUAGE="JAVASCRIPT" TYPE="TEXT/JAVASCRIPT">
<!--
if (url==http://mysiteaddress/index.html)
{document.write('Welcome to my site')}
//-->
</SCRIPT>
Taking out the if statement, it successfully writes 'Welcome to My site'. So I'm wondering what is wrong with the if statement. I've also tried adding an 'else' in order to see output on any page but have not had any luck.
I obviously don't know much yet so any help would be appreciated. Thanks!
The url is available via location.href - not sure why you think url exists.
Besides that, mime types are lowercase and the language attribute is obsolete. So use <script type="text/javascript">.
Additionally it'd be better if you didn't use the infamous document.write but document.getElementById('someDiv').innerHTML = 'your html here';
Or get jQuery and simply write $('#someDiv').html('your html here');
Just to add, you can prepend an element to the body element like this:
var p = document.createElement("p");
p.innerHTML = "I am a paragraph";
document.body.insertBefore(p, document.body.firstChild);
You can try it here.
Reference: https://developer.mozilla.org/En/DOM/Node.insertBefore