Is onclick embedded JavaScript? - javascript

This may be a subjective question. If so please close it.
Does onclick count as embedded JavaScript?
Or is it just usually the method called that’s actually the JavaScript part?

I’m not sure what you’re asking, but I’ll have a go anyway.
The onclick attribute that you can add to HTML elements (i.e. <a onclick="">) is HTML. However, its value is JavaScript that gets run when the user clicks on the element. That JavaScript (along with the association between that JavaScript and the HTML element’s click event) is indeed embedded in the HTML page, meaning you have to change your HTML page to change the JavaScript (or remove the association).
To avoid embedding JavaScript into your HTML page, you can instead add a handler function to the onclick DOM property of an element via JavaScript:
Add a JavaScript file to your page, via the <script src=""> tag.
In that file, set some code to run on page load (or when the DOM is ready, which is a whole other topic in itself).
Have that code add an onclick handler function to an HTML element.
E.g. if your HTML looked like this
<a id="needs_onclick">I need an onclick handler</a>
Then you could add an onclick handler to the link like this:
window.onload = function(){
document.getElementById("needs_onclick").onclick = function(){
alert("Clicked!");
}
}
This approach would not be described as “embedded JavaScript”, as it uses the onclick DOM property, not the onclick attribute.

(...) functions called "Event Handlers." These are commands that work
directly with existing HTML commands. They work so closely in fact,
they work by being embedded right into the HTML command itself.
The source: http://www.htmlgoodies.com/beyond/javascript/article.php/3470771/Advanced-JavaScript-for-Web-Developers-onClick-and-onMouseOver.htm
From mighty Google. Took me about 15 seconds to find it.

Related

How to remove Custom GTM HTML Tags from DOM after firing?

For single page applications I was wondering if it's possible to remove a custom gtm html tag from the DOM after it has been fired.
The idea behind this is to avoid an uncontrollable growing of the DOM through custom scripts.
I've encountered the same problem in a recent project I've been working on. However, I haven't found any 'native' solution for it, mainly because every Tag that can be injected with GTM can inject code in a totally different way.
What I have ended doing for this project is implement a rather simple solution (even if not perfect), which consists in:
Include a unique ID for every "Custom Tag" in GTM, with a common prefix that can be stored inside a variable (SCRIPT_ID). A CSS class would be better, but GTM seems to ignore them at all.
<script id="{{SCRIPT_ID}}__PIXEL_ID">
... custom code ...
</script>
Create a function that searches and removes any script inside the <body> tag (where GTM injects the Tags) with an ID that starts with the previous prefix.
function flushScripts() {
const pixels = document.body.querySelectorAll(':scope > script[id^="SCRIPT_ID"]');
for (const p of pixels) { document.body.removeChild(p); }
}
Execute that function every time the route changes or every time you see fit.

HTML attributes that can contain javascript

I'm looking for a simple list of all the html attributes that can contain javascript that will automatically run when an action is performed. I know this will differ between browsers and versions but I'd rather be safer than sorry. I currently know of the following javascript attributes: onload, onclick, onchange, onmouseover, onmouseout, onmousedown, and onmouseup
Backstory:
I'm getting a full html document from an untrusted source and I want to strip all javascript that could run from the original html document so I'm removing all script tags as well as any attributes that could hold javascript before its displayed in an iframe. For this implantation there is no server side processing and no way of sandboxing the code since I need to run javascript that is being added locally after all of the original javascript is removed.
There are two places where Javascript can be used in HTML attributes:
Any onEVENT attribute. I suggest just treating any attribute that begins with on as an event binding, and strip them all out.
Any attribute that can contain a URI will be executed as Javascript if the URI uses the javascript: scheme, such as href and src. A complete list is in
COMPLETE list of HTML tag attributes which have a URL value?
http://www.w3.org/TR/html401/interact/scripts.html#h-18.2.3
Scroll down to 18.2.3 Intrinsic events
I've had a similar requirement in a project. Don't forget to strip script elements, as well.

JQuery selector of script tag calling from

i have the following html output of a tool thats i'm developing:
<button>a</button>
<script>$('what to wrtie here to select the previous button element?').click(function(){alert ('a clicked !');});</script>
<button>b</button>
<script>$('same here').click(function(){alert ('b clicked !');});</script>
i need the selector in each script tag to select the previous element.
using id selector cant be applied since the tool don't generate ids for elements.
thanks.
ANSWER:
$('script').last().prev().click(...
as Niklas said the current executed script is the last one in the list
This is not possible without an id or some other kind of reference to either the button object or the script tag itself.
It's not possible to do because the script is not executed from where its element is located in the DOM. Instead it's executed with reference to the whole window.
Actually, there's a pretty good answer here: How may I reference the script tag that loaded the currently-executing script?
In short, the currently running script is the last element in the list.
well , i really don't recommend what you are doing first lets talk about your approach,
this kind of code should be wrapped in a ready event and when the DOM is ready all the registered code associated with that event will run , so no way to understand what script tag the code were in
what should happen is moving all the script tags to its own file and using selectors to select what elements you want or selecting them dynamicly using prev,next, parents, etc
Edit
i am wrong about not being able to get the script tag #Niklas answer is the right one, but i am still thinking very wrong to do so
There is no way of doing this (referring to the script tag that contains the script) that I know of. The best approach here would be to generate an ID for each element and aggregate your script into a single script tag.
That up there is the correct solution. The secret, naughty solution is this (spoiler):
<button>a</button><script>
//script#0001
$('script:contains("#0001")').prev().click(function(){
alert('foo');
});</script><button>b</button><script>
//script#0002
$('script:contains("#0002")').prev().click(function(){
alert('bar'); });</script>
DON'T USE IT

Best way to execute Javascript on an anchor

Generally, there are 3 ways (that I am aware of) to execute javascript from an <a/> tag:
1) Use onclick():
hello
2) Directly link:
hello
3) Or attach externally:
// In an onload event or similar
document.getElementById('hello').onclick = window.alert('Hello');
return false;
<a id="hello" href="#">hello</a>
I am actually loading the link via AJAX, so #3 is basically out. So, is it better to do #1 or #2 or something completely different? Also, why? What are the pitfalls that I should be aware of?
Also of note, the anchor really doesn't link anywhere, hence the href="#", I am using a so the styles conform as this is still an object to be clicked and a button is inappropriate in the context.
Thanks
If you are loading the content via ajax and need to hook up event handlers, then you have these choices:
Put a javascript handler in your HTML with your option 1) or 2). In my mind option 1) is a cleaner way of specifying it, but I don't think there's a mountain of difference between 1) or 2) - they both do essentially the same thing. I'm not a fan of this option in general because I think there's value in keeping the markup and the code separate.
After loading the content with ajax, call some local code that will find and hook up all the links. This would be the same kind of code you would have in your page and execute on DOMReady if the HTML had been static HTML in your page. I would use addEventListener (falling back to attachEvent) to hook up this way as it more cleanly allows multiple listeners for a single object.
Call some code after you load the content with ajax that finds all the links and hooks up the clicks to some generic click handler that can then examine meta data in the link and figure out what should be done on that click based on the meta data. For example, this meta data could be attributes on the clicked link.
When you load the content, also load code that can find each link individually and hook up an appropriate event handler for each link much the way one would do it if the content was just being loaded in a regular page. This would meet the desire of separating HTML from JS as the JS would find each appropriate link and hook up an event handler for it with addEventListener or attachEvent.
Much like jQuery .live() works, hook up a generic event handler for unhandled clicks on links at the document level and dispatch each click based on some meta data in the link.
Run some code that uses an actual framework like jQuery's .live() capability rather than building your own capability.
Which I would use would depend a little on the circumstances.
First of all, of your three options for attaching an event handler, I'd use a new option #4. I'd use addEventListener (falling back to attachEvent for old versions of IE) rather than assigning to onclick because this more cleanly allows for multiple listeners on an item. If it were me, I'd be using a framework (jQuery or YUI) that makes the cross browser compatibility invisible. This allows complete separation of HTML and JS (no JS inline with the HTML) which I think is desirable in any project involving more than one person and just seems cleaner to me..
Then, it's just a question for me for which of the options above I'd use to run the code that hooks up these event listeners.
If there were a lot of different snippets of HTML that I was dynamically loading and it would be cleaner if they were all "standalone" and separately maintainable, then I would want to load both HTML and relevant code at the same time so have the newly loaded code handle hooking up to it's appropriate links.
If a generic standalone system wasn't really required because there were only a few snippets to be loaded and the code to handle them could be pre-included in the page, then I'd probably just make a function call after the HTML snippet was loaded via ajax to have the javascript hook up to the links in the snippet that had just been loaded. This would maintain the complete separation between HTML and JS, but be pretty easy to implement. You could put some sort of key object in each snippet that would identify which piece of JS to call or could be used as a parameter to pass to the JS or the JS could just examine the snippet to see which objects were available and hook up to whichever ones were present.
Number 3 is not "out" if you want to load via AJAX.
var link = document.createElement("a");
//Add attributes (href, text, etc...)
link.onclick = function () { //This has to be a function, not a string
//Handle the click
return false; //to prevent following the link
};
parent.appendChild(link); //Add it to the DOM
Modern browsers support a Content Security Policy or CSP. This is the highest level of web security and strongly recommended if you can apply it because it completely blocks all XSS attacks.
The way that CSP does this is disabling all the vectors where a user could inject Javascript into a page - in your question that is both options 1 and 2 (especially 1).
For this reason best practice is always option 3, as any other option will break if CSP is enabled.
I'm a firm believer of separating javascript from markup. There should be a distinct difference, IMHO, between what is for display purposes and what is for execution purposes. With that said, avoid using onclick attribute and embedding javascript:* in a href attribute.
Alternatives?
You can include javascript library files using AJAX.
You can setup javascript to look for changes in the DOM (i.e. if it's a "standard task", make the anchor use a CSS class name that can be used to bind a specific mechanism when it's later added dynamically. (jQuery does a great job at this with .delegate()))
Run your scripts POST-AJAX call. (Bring in the new content, then use javascript to [re]bind the functionality) e.g.:
function ajaxCallback(content){
// add content to dom
// search within newly added content for elements that need binding
}

popup balloon in JQuery

I used the following command to make a popup balloon each time mouse move on a div tag in a web page and I am trying to insert this command in any web page I am parsing so I append the command in the head as follows:
head.append("$('div').attr('onmouseover', 'balloon.showTooltip(event,You are hovering, I said click me! <a href=www.google.com>Click</a>)');");
where
ballon is the object I defined it previously
But it does not work
Besides not understanding what the question really is, there are a lot of things wrong with this code. The main issue I see is that the showTooltip function call is not legal javascript because the message is not a quoted string. In addition, this is not a good way to use event handlers in jQuery. Assuming that head is a jQuery object in your page (and not the head tag), try this:
head.append($("<div class='test'>").mouseover(function() {
balloon.showTooltip(event, "You are hovering, I said click me! <a href='http://www.google.com'>Click</a>");
});
The other issue with this is that the <div> that you create and append to the page has no size so you can never get a mouseover event on it. If you give it a finite size, it can work. You can see that here: http://jsfiddle.net/jfriend00/Y6LGT/ where I give it a class name and use CSS to give it a size.

Categories

Resources