This question already has answers here:
Dynamically adding script element to a div does not execute the script
(2 answers)
Closed 5 years ago.
I am trying to insert Javascript code into HTML via Javascript.
Inserting this code into HTML does not work, the code is not executed :
<script>
function callAlert(){
alert('test');
}
</script>
This code is executed :
<img src="xxx" onerror="alert('test')">
This does not call the function so the alert is not executed :
<img src="xxx" onerror="callAlert();">
Why onerror alert is executed and onerror calling function not?
You can no longer insert a <script> tag using el.innerHTML. This is a security issue that has been added fairly recently.
Go to this page:
https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
and scroll down to the Security considerations section.
It mentions that you can not add a <script> tag but it is not fool proof. Things like you describe can still cause script to run:
const name = "<img src='x' onerror='alert(1)'>";
el.innerHTML = name; // shows the alert
If you really need to add new JavaScript from existing JavaScript you will need to do something like the following:
var s = document.createElement('script');
s.textContent = 'function callAlert(){alert(\'test\');}';
document.head.appendChild(s);
callAlert();
Try putting the script into the head of the page, it could be that the function is executed before it's defiend.
If this isn't working please tell what error your console returns.
Related
This question already has answers here:
How to include jQuery dynamically in any website using pure javascript
(9 answers)
Closed 25 days ago.
How do I continue executing my .js code after programmatically adding jQuery to the DOM?
The 3rd answer in this post shows how to add jquery to the dom but how should you continue executing further code?
For example you can't just add code underneath the self invoked function because jQuery hasn't yet loaded. How do I continue writing my .js code so that it executes?
$(window).on('load', function() {
// jQuery hasn't yet loaded so can't use this yet.
});
Execute the code that requires jQuery in the script's load event listener.
var jQueryScript = document.createElement('script');
jQueryScript.setAttribute('src','https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js');
jQueryScript.addEventListener("load", function() {
$(document).ready(function() {
...
});
});
document.head.appendChild(jQueryScript);
This question already has answers here:
Javascript variables in HTML attributes
(5 answers)
Closed 4 years ago.
Passing a javascript variable using tag in iframe by attaching variable like this "+var+" but its not passing value to next page . is there any different way or any bug in my code please suggest.
here is my code.
<script>
var user = "user#user.com";
</script>
<iframe src="http://127.0.0.1/ve2/ve2/www/kitchen-sink/api/fm/df.php?user="+user+""></iframe>
Thanks in advance .
You cannot execute javascript directly, it has to be executed from script tags OR via an event.
<iframe id="iframe"></iframe>
<script>
var iframe = document.getElementById('iframe');
var user = "user#user.com";
iframe.setAttribute('src', "http://127.0.0.1/ve2/ve2/www/kitchen-sink/api/fm/df.php?user=" + user );
</script>
This question already has answers here:
Can you make a javascript function replace itself on the page with custom html?
(4 answers)
Closed 5 years ago.
I need to create a javascript that return a iframe tag.
the customer will paste a script in where the iframe need to be, and then the script should create a iframe.
Must be like this:
<script src="http://www.helloworld.com/script/loadcustomerframe.js" data-customer="14532"></script>
then the script should load a iframe to a url somewhere, and also i need to read the "data-customer".
I am a backend developer c#, not a frontend. I have try several days now, i cant get it to work.
Please help.
Thanks
Something like this should work:
$(document).ready(() => {
$("[data-customer]").each(function() {
let customerId = $(this).data("customer");
$(this).replaceWith(`<p>This is customer #${customerId}.</p>`);
// The following comment is an example of how you could use an iframe
//$(this).replaceWith(`<iframe src="http://example.org/customer/${customerId}>Hello!</iframe>`);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-customer="1"></div>
<div data-customer="2"></div>
<div data-customer="3"></div>
You'll only need to have the script appear once (most likely in your <head>) and it will replace any <div> that has a data-customer attribute. You simply just need to figure out the proper URL for your <iframe>.
Si basically your JS code will do the trick,
First need to create a JS code and host it into some server to get it by fetching it, so image that your JS code is hosted into https://www.mygreatjscode.com/myjscode.js
So your JS code will do the rest,
like this using pure JS (with not frameworks like jQuery etc), so your myjscode.js file will contain this:
//create an autoexec function
(function(){
var body = document.getElementByTagName("body");
body = body ? body : false;
if (body){
var iframe = document.createElement("iframe");
iframe.setAttribute("id", "MY_CUSTOM_ID");
//here set the url that the iframe will be render
iframe.setAttribute("src", "https://stackoverflow.com/");
//finally insert into the body of page
body.appendChild(iframe);
}
})();
Finally you need to insert the Script Tag into your page like this
<script src="https://www.mygreatjscode.com/myjscode.js" data-customer="14532"></script>
This question already has answers here:
Executing <script> injected by innerHTML after AJAX call
(12 answers)
Closed 5 years ago.
I have a site which loads content through AJAX. I need to attach onclick handler to some div which was dynamically loaded. It works fine if my event handler is already defined in my main javascript file (whether I attach it through markup via attribute onclick="myFunc" on by more pedantic addEventListener ).
However, I would like this event handler to be defined in a <script> tag of the dynamically loaded content. Then it doesn't work, whether <script>function myHandler(){}</script> is before or after the <div onclick='myHandler();'>.
I tried to attach it at the end of the XmlHttpRequest:
contentDiv.innerHTML = xhr.responseText;
var handlerName = getItFrom(xhr.responseText);
var clickFn = window[handlerName];
loadedDiv.addEventListener('click', clickFn);
Doesn't work neither: handlerName is correct, but clickFn remains undefined...
I prefer a pure js answer but jquery is ok if I can easily translate it.
It's doable if you're willing to use jQuery, here I assign an event handler from a script tag of a html string. A couple of things, the parameter you pass into .html has to be a jQuery object of your string, and you'll need to replace </script> with <\/script> within the string (could use .replace).
$('#content').html($("<span>before</span><script>$('#testo').click(function () { alert('infunc');});<\/script><span>after</span>"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='content'></div>
<button id='testo'>Click</button>
If getItFrom(xhr.responseText); returns a function defined in the global scope try to add quotes like this:
var clickFn = window['handlerName'];
Because console says:
var luck = function(){}; window[luck];
> undefined
var luck = function(){}; window['luck'];
> function luck()
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript that executes after page load
how to call a javascript method as soon as page is loaded.
i have a java script which needs to be called soon after the jsp page is loaded, how to achieve this in javascript.
could any one of you help me pelase.
Regards
You can write a code snippet something like this :-
window.onload(function(){
//Your JavaScript here
});
And if using JQuery then
document.ready(function(){
//Your JavaScript Here
});
Or you can have all your JS after all the HTML.
you can even use a function called :--
document.onload(function(){
//Your code Here
});
Last but not the least you could even try out this
<body onload="YourJSMethod();">
<!-- Some html content -->
</body>
you can try
<body onload="someMethod();">
<!-- Some html content -->
</body>
This will call your method as soon as body tag of your page is loaded.
Alternatively you can make use of jquery's document ready function.
$(document).ready(function() {
// your code
});