The “clickjacking” attack allows an evil page to click on a “victim site” on behalf of the visitor.… we need to attack – is to position the <iframe> on the evil page in such a way that the button… Technically, if we have a text field to hack, then we can position an iframe in such a way that text… So we can add the iframe with sandbox="allow-scripts allow-forms".… Use a covering <div> if we want to allow our pages to be shown in iframes, but still stay safe.
CSS animations make it possible to do simple animations without JavaScript at all.… JavaScript can be used to control CSS animations and make them even better, with little code.… CSS properties with a word cubic-bezier will have an icon before this word.… It is widely used to do an action after the animation is done. Also we can join animations.… Limitations of CSS animations compared to JavaScript animations:
MeritsSimple things done
JavaScript was initially created to “make web pages alive”.… They don’t need special preparation or compilation to run.… For instance, in-browser JavaScript is able to:
Add new HTML to the page, change the existing content… The aim is to prevent an evil webpage from accessing private information or harming the user’s data.… It has no direct access to OS functions.
For instance, to assign a click handler for an input, we can use onclick, like here:… An HTML-attribute is not a convenient place to write a lot of code, so we’d better create a JavaScript… Multiple calls to addEventListener allow it to add multiple handlers, like this:… Event object.To properly handle an event we’d want to know more about what’s happened.… Methods: elem.addEventListener(event, handler[, phase]) to add, removeEventListener to remove.
In this chapter we’ll cover how an object converts to primitive and how to customize it.… They’re called “hints”, as described in the specification:
"string"
For an object-to-string… "number"
For an object-to-number conversion… So if a binary plus gets an object as an argument, it uses the "default" hint to convert it… They provide an alternative “old-style” way to implement the conversion.
Iframe: wrong document pitfall.When an iframe comes from the same origin, and we may access its document… Upon its creation an iframe immediately has a document.… Allows to submit forms from iframe.
allow-scripts
Allows to run scripts from the iframe.
allow-popups… is the window inside an <iframe> tag.… That can be used to run untrusted code in iframes from the same site.
There are generally two ways to style an element:
Create a class in CSS and add it: <div class="… We should always prefer CSS classes to style.… If we set style.display to an empty string, then the browser applies CSS classes and its built-in styles… Mind the units.Don’t forget to add CSS units to values.… The result is an object with styles, like elem.style, but now with respect to all CSS classes.
The browser allows us to track the loading of external resources – scripts, iframes, pictures and so… For <iframe>, the iframe.onload event triggers when the iframe loading finished, both for successful… load and in case of an error.… To allow cross-origin access, the <script> tag needs to have the crossorigin attribute, plus the… Let’s add it.
But as it’s forbidden to access the content of an <iframe> from another site, it wasn’t possible… To be precise, there were actually tricks for that, they required special scripts at both the iframe… add Access-Control-Allow-Origin to the main response.… To send credentials in fetch, we need to add the option credentials: "include", like this:… That’s an additional safety measure, to ensure that the server really knows who it trusts to make such
Most JavaScript methods deal with one of two coordinate systems:
Relative to the window – similar to… To show something near an element, we can use getBoundingClientRect to get its coordinates, and then… show the message at the left, right, below, apply CSS animations to “fade it in” and so on.… In CSS, window coordinates correspond to position:fixed, while document coordinates are similar to position… There’s no standard method to get the document coordinates of an element.
The scroll event allows reacting to a page or element scrolling.… Here’s a small function to show the current scroll:… If we add an event handler to these events and event.preventDefault() in it, then the scroll won’t start… There are many ways to initiate a scroll, so it’s more reliable to use CSS, overflow property.… Here are few tasks that you can solve or look through to see applications of onscroll.
HTML/CSS properties.… That built-in method allows to setup a callback function to run when the browser will be preparing a… to draw the animation.… So you’d want to add the features that you need when you need them.… Unlike CSS, we are not limited to Bezier curves here.
How to get an arbitrary element of the page?… Here in the tutorial we use id to directly reference an element for brevity, when it’s obvious where… querySelector.The call to elem.querySelector(css) returns the first element for the given CSS selector… Besides that:
There is elem.matches(css) to check if elem matches the given CSS selector.… There is elem.closest(css) to look for the nearest ancestor that matches the given CSS-selector.
CSSOM for styling
There’s also a separate specification, CSS Object Model (CSSOM) for CSS… In practice though, the CSSOM is rarely required, because we rarely need to modify CSS rules from JavaScript… (usually we just add/remove CSS classes, not modify their CSS rules), but that’s also possible.… The location object allows us to read the current URL and can redirect the browser to a new one.… To find something, it’s often convenient to use an internet search “WHATWG [term]” or “MDN [term]”, e.g
Let’s add the g flag to find all digits:… For instance, CSS\d matches a string CSS with a digit after it:… An alternative, shorter way is to find non-digits \D and remove them from the string:… Pay attention to spaces
Usually we pay little attention to spaces.… We can’t add or remove spaces from a regular expression and expect it to work the same.
And there’s an object with methods save, load, search… How to match them?… The “behavior” pattern.We can also use event delegation to add “behaviors” to elements declaratively,… The pattern has two parts:
We add a custom attribute to an element that describes its behavior.… We can add new ones to HTML at any moment.… Now, to add toggling functionality to an element – there’s no need to know JavaScript, just use the attribute
We can use this to check if an element is hidden, like this:… We can use these properties to expand the element wide to its full width/height.… So why not to read the width of an element with getComputedStyle, like this?… “what is” CSS width and height.… Second, CSS width/height may be auto, for instance for an inline element:
But just as we expose methods to interact with our component, we can expose CSS variables (custom CSS… properties) to style it.… For example, in shadow DOM we can use --user-card-field-color CSS variable to style fields, and the… They are used as “hooks” to style the component:
The component uses a custom CSS property to style key… When a developer wants to style a title, they assign --component-name-title CSS property for the shadow
Or, at least, close to it?… CSS styles, applied to the component.… Usually, special CSS classes and conventions are used to provide “component feel” – CSS scoping and DOM… Shadow DOM – to create an internal DOM for the component, hidden from the others.… CSS Scoping – to declare styles that only apply inside the Shadow DOM of the component.
If we handle an event in JavaScript, we may not want the corresponding browser action to happen, and… We can add nested lists and style them using CSS to “slide down”.… For instance, mousedown on an <input> field leads to focusing in it, and the focus event.… How to fix it?… An alternative solution would be to check in the document handler if the default action was prevented
has to wait.… Naturally, it has to wait for styles to load.… If we want to cancel the transition to another page, we can’t do it here.… the message shown to the user.… a string to get the result similar to the code above:
Although, we may need to add touch-action: none in some places in CSS.… Here is the flow of user actions and the corresponding events:
The user presses on an image, to start… To avoid problems with them too:
Prevent them by setting #ball { touch-action: none } in CSS.… Now we can add the code to actually move the ball, and our drag’n’drop will work for mouse devices and… own – remember to cancel the default action on events and set touch-action: none in CSS for elements
In this chapter we’ll pay attention to separate these two notions, to see how to work with them, when… We can assign anything to an attribute, but it becomes a string.… Sometimes non-standard attributes are used to pass custom data from HTML to JavaScript, or to “mark”… Because an attribute is more convenient to manage.… Then CSS updates the view accordingly: in the example above the last line (*) changes the color to blue
Even if we’d like to force Mac users to Ctrl+click – that’s kind of difficult.… There are also mobile devices
Keyboard combinations are good as an addition to the workflow… Move the mouse over the input field to see clientX/clientY (the example is in the iframe, so coordinates… are relative to that iframe):… knows how to do it.
According to the Document Object Model (DOM), every HTML tag is an object.… Another way to explore the DOM is to use the browser developer tools.… At the right part of the tools there are the following subtabs:
Styles – we can see CSS applied to the… Computed – to see CSS applied to the element by property: for each property we can see a rule that gives… Like: get a node and run some code to modify it, to see the result.
To apply alternation to a chosen part of the pattern, we can enclose it in parentheses:
I love HTML|… CSS matches I love HTML or CSS.… I love (HTML|CSS) matches I love HTML or I love CSS.… Next, minutes must be from 00 to 59.… The alternation | now happens to be between [01]\d and 2[0-3]:[0-5]\d.
a class to it or whatever).… Later we’ll see how to add other features, such as highlighting current underlying elements while we… Here’s an example in action:
Try to drag’n’drop with the mouse and you’ll see such behavior… There’s no way to catch an event on the blue one, because the red is on top:… An extended code of onMouseMove to find “droppable” elements:
One way is to loop over them as over an array:… If they were any other type, like a number, or an object, they would get converted to a string automatically… You might want to open this page in two browser windows to test the code below.… We may even want to set something back in it, to “respond” to a change.… Use Object.keys to get all keys.
Arguments of these methods are an arbitrary list of DOM nodes to insert, or text strings (that become… Here’s an example of using these methods to add items to a list and the text before/after it:… But what if we’d like to insert an HTML string “as html”, with all tags and stuff working, in the same… move an element to another place – there’s no need to remove it from the old one.… Why append to a special kind of node, if we can return an array of nodes instead?
That’s possible, but if we’re moving elements to shadow DOM, then CSS styles from the document do not… For example, let’s add the default slot to our <user-card> that shows all unslotted information… We just need to add a click handler to open/close the list, and the <custom-menu> is ready:… Updating slots.What if the outer code wants to add/remove menu items dynamically?… So we don’t have to do anything to update rendering.
Such as <input type="range">:
The browser uses DOM/CSS internally to draw them.… Chronologically, browsers first started to experiment with internal DOM structures to implement controls… , and then, after time, shadow DOM was standardized to allow us, developers, to do the similar thing.… There’s no way to access them.… as append, to populate it.
Then, the browser automatically adds them to (almost) every request to the same domain using the Cookie… An assignment to it is treated specially.… max-age=3600
It’s an alternative to expires and specifies the cookie’s expiration in seconds from the… adds an exception.… But we can use samesite together with other protection measures, like xsrf tokens, to add a layer of
Bezier curves are used in computer graphics to draw shapes, for CSS animation and in many other places… After some practice it becomes obvious how to place points to get the needed curve.… As t runs from 0 to 1, every value of t adds a point to the curve.… to t from the beginning.… In CSS animation to describe the path and speed of animation.
add the behavior to other classes.… A mixin example.The simplest way to implement a mixin in JavaScript is to make an object with useful… So let’s make a mixin that allows us to easily add event-related functions to any class/object.… After adding the mixin, an object user will be able to generate an event "login" when the visitor… And eventMixin mixin makes it easy to add such behavior to as many classes as we’d like, without interfering
But the Origin header is important, as it allows the server to decide whether or not to talk WebSocket… An extension is something related to transferring the data, functionality that extends the WebSocket… But for binary processing, to access individual data bytes, we can change it to "arraybuffer"… In particular, codes lower than 1000 are reserved, there’ll be an error if we try to set such a code.… For each accepted websocket, add it to the set clients.add(socket) and set message event listener to
It supports two operations:
push adds an element to the end.
pop takes an element from the end.… We can add any properties to them.… The ways to misuse an array:
Add a non-numeric property like arr.test = 5.… The similar thing happens with unshift: to add an element to the beginning of the array, we need first… We can use an array as a deque with the following operations:
push(...items) adds items to the end.
To create a custom element, we need to tell the browser several details about it: how to show it, what… to do when the element is added or removed to page, etc.… Usually, when we change an attribute, like a.href, we expect the change to be immediately visible.… If we’d like to pass information to custom element, we can use attributes.… At the end, to use our custom element, insert a regular <button> tag, but add is="hello-button
But we forgot to re-test f(1). That may lead to an error.
That’s very typical.… Development of “pow”: the spec.Let’s say we want to make a function pow(x, n) that raises x to an integer… The function does not work: an attempt to calculate pow(3,4) would give an incorrect result, but tests… We need to add more use cases to it.
Let’s add one more test to check that pow(3, 4) = 81.… Let’s first add the behavior to the spec(!)
A popup window is one of the oldest methods to show additional document to user.… open a popup is: window.open(url, name, params):
url
An URL to load into the new window.
name
A name… There is a limit on minimal width/height, so it’s impossible to create an invisible window.… If we’re going to open a popup, a good practice is to inform the user about it.… An “opening window” icon near a link or button would allow the visitor to survive the focus shift and
(...items) – adds items to the end,
arr.pop() – extracts an item from the end,
arr.shift() – extracts… an item from the beginning,
arr.unshift(...items) – adds items to the beginning.… Here are a few others.
splice.How to delete an element from the array?… To sort it, we need an ordering function that knows how to compare its elements.… Summary.A cheat sheet of array methods:
To add/remove elements:
push(...items) – adds items to the
For instance, in the code below the ask function accepts a question to ask and an arbitrary number of… Here we add the counter property to track the total calls count:… And add a name to it:… And func is an “internal function name”, the way for the function to can call itself reliably.… The lodash library creates a function _, and then adds _.clone, _.keyBy and other properties to it (see
As you might have guessed, it’s the object to represent HTML form data.… have many fields with the same name, so multiple calls to append add more same-named fields.… send dynamically generated binary data e.g. an image, as Blob.… In practice though, it’s often convenient to send an image not separately, but as a part of the form,… We can either create new FormData(form) from an HTML form, or create an object without a form at all,
config is an object with boolean options “what kind of changes to react on”:
childList… Imagine the situation when you need to add a third-party script that contains useful functionality, but… to detect, when it happens, to adapt our page, dynamically resize something etc.… We could append that call to the code that loads an article, like this:… add syntax highlighting to it.
For that, the ECMA standard specifies an internal queue PromiseJobs, more often referred to as the “microtask… Or, to put it more simply, when a promise is ready, its .then/catch/finally handlers are put into the… Now we can see exactly how JavaScript finds out that there was an unhandled rejection.… Normally, if we expect an error, we add .catch to the promise chain to handle it:… If we need to guarantee that a piece of code is executed after .then/catch/finally, we can add it into
In other words, we want to add an iteration ability to the object.… To iterate over such an object, we should use a for await (let item of iterable) loop.… To iterate, we use for await(let value of range) (4), namely add “await” after “for”.… Most of the time, when we’d like to make an iterable, we’ll use generators.… make an object iterable, we should add Symbol.iterator to it.
to the list at https://tc39.github.io/ecma262/ and then progress to the specification.… So it’s quite common for an engine to implement only part of the standard.… So, if a visitor uses an outdated browser, it may fail to understand the code like height = height ??… Summary.In this chapter we’d like to motivate you to study modern and even “bleeding-edge” language features… Just don’t forget to use a transpiler (if using modern syntax or operators) and polyfills (to add functions
First we’ll look at the details, and then how to use it for adding new capabilities to built-in objects… For instance, if we add a method to String.prototype, it becomes available to all strings:… have, and we may be tempted to add them to native prototypes.… For instance, if we’re making an array-like object, we may want to copy some Array methods to it.… But it’s not recommended to change them.
So, to summarize, a symbol is a “primitive unique value” with an optional description.… We’d like to add identifiers to them.… As user objects belong to another codebase, it’s unsafe to add fields to them, since we might affect… The third-party code won’t be aware of newly defined symbols, so it’s safe to add symbols to the user… If we want to add a property into an object that “belongs” to another script or a library, we can create
Add the item to their inventory.… After the transaction is created, we can add an item to the store, like this:… An index is an “add-on” to the store that tracks a given object field.… The index will enforce that by generating an error if we try to add a duplicate.
multiEntry – only used… Then getAll will fail to get all records as an array.
What to do?
For instance, if we put an object into an array, then while the array is alive, the object will be alive… If an object has lost all other references (like john in the code above), then it is to be garbage-collected… If we’re working with an object that “belongs” to another code, maybe even a third-party library, and… WeakSet.WeakSet behaves similarly:
It is analogous to Set, but we may only add objects to WeakSet (not… For instance, we can add users to WeakSet to keep track of those who visited our site:
Only first 50 results are shown.