597 Matching Annotations
  1. Last 7 days
  2. Nov 2022
    1. There are plenty of articles about the emergence of PyScript for embedding Python code directly into HTML, but until now the creation of browser extensions in Python has been something of a closed door.

      One can use PyScript to write browser extensions in Python (or at least some simple ones?)

    1. 🧐 Why is there no event.preventDefault on the button? A <button type="button">, while seemingly redundant, is the HTML way of preventing a button from submitting its form.
  3. Sep 2022
  4. Aug 2022
    1. Even if the browser ignores the closing slash in void tags, it's good practice to close it because: 1. in frameworks like react js if these are not close, it creates an error 2. if you want your document to be readable by an XML parser then must close all elements
    1. ```html

      <div class="select-container" data-content=""> <select class="select" id="words"> <option value="lorem ipsum dolor sit amet">Lorem ipsum dolor sit amet</option> <option value="lorem">Lorem</option> <option value="ipsum">Ipsum</option> <option value="dolor">Dolor</option> <option value="sit">Sit</option> <option value="amet">Amet</option> </select> </div>

      css .select { color: transparent; appearance: none; padding: 5px; background: transparent url("https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-arrow-down-b-128.png") no-repeat calc(~"100% - 5px") 7px; background-size: 10px 10px; }

      .select-container { position: relative; display: inline-block; }

      .select-container::before { content: attr(data-content); pointer-events: none; position: absolute; top: 0; right: 10px; bottom: 0; left: 0; padding: 7px; font: 11px Arial, sans-serif; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; text-transform: capitalize; } js const selectContainer = document.querySelector(".select-container"); const select = selectContainer.querySelector(".select");

      select.value = "lorem ipsum dolor sit amet"; selectContainer.dataset.content = select.value;

      function handleChange(e) { selectContainer.dataset.content = e.currentTarget.value; }

      select.addEventListener("change", handleChange); ```

    1. ```html

      <div class="select-sim" id="select-color"> <div class="options"> <div class="option"> <input type="radio" name="color" value="" id="color-" checked /> <label for="color-"> Select an option </label> </div> <div class="option"> <input type="radio" name="color" value="red" id="color-red" /> <label for="color-red"> Red </label> </div> <div class="option"> <input type="radio" name="color" value="green" id="color-green" /> <label for="color-green"> Green </label> </div> <div class="option"> <input type="radio" name="color" value="blue" id="color-blue" /> <label for="color-blue"> Blue </label> </div> <div class="option"> <input type="radio" name="color" value="yellow" id="color-yellow" /> <label for="color-yellow"> Yellow </label> </div> <div class="option"> <input type="radio" name="color" value="pink" id="color-pink" /> <label for="color-pink"> Pink </label> </div> <div class="option"> <input type="radio" name="color" value="turquoise" id="color-turquoise" /> <label for="color-turquoise"> Turquoise </label> </div> </div> </div>


    1. Sanitizing iframes


      <iframe id="webpage"></iframe>

      <br/> <button onclick="sanitize()">Sanitize</button>

      <script> function sanitize() { // Create a sanitizer object with the default config const sanitizer = new Sanitizer(); // Find the iframe node const iframe = document.getElementById('webpage'); // Sanitize the iframe's document node const sanitizedFrameNodes = sanitizer.sanitize(iframe.contentWindow.document); iframe.replaceChildren(sanitizeFrameNodes); } </script>


    1. The setHTML() method of the Element interface is used to parse and sanitize a string of HTML and then insert it into the DOM as a subtree of the element. It should be used instead of Element.innerHTML for inserting untrusted strings of HTML into an element.

      ```js const unsanitized_string = "abc <script>alert(1)<" + "/script> def"; // Unsanitized string of HTML const sanitizer1 = new Sanitizer(); // Default sanitizer;

      // Get the Element with id "target" and set it with the sanitized string. document.getElementById("target").setHTML(unsanitized_string, {sanitizer: sanitizer1});

      // Result (as a string): "abc def" ```

    1. If you're using JavaScript for writing to a HTML Attribute, look at the .setAttribute and [attribute] methods which will automatically HTML Attribute Encode. Those are Safe Sinks as long as the attribute name is hardcoded and innocuous, like id or class.
    2. If you're using JavaScript for writing to HTML, look at the .textContent attribute as it is a Safe Sink and will automatically HTML Entity Encode.
    1. js function transclude(elementId) { var clone = document.getElementById(elementId).cloneNode(true), placeholder; clone.id = null; document.write('<br id="__placeholder__">'); placeholder = document.getElementById('__placeholder__'); placeholder.parentNode.insertBefore(clone, placeholder); placeholder.parentNode.removeChild(placeholder); return transclude; }


      This is paragraph 1.

      This is paragraph 2.

      This is paragraph 3. It should contain paragraphs 1 and 2. <script>transclude("p1")("p2")</script>


    1. 这种单独使用的标签,通常是因为标签本身就足够完成功能了,不需要标签之间的内容。实际应用中,它们主要用来提示浏览器,做一些特别处理


  5. Jul 2022
    1. And immediately after it, the 2 CSS downloads begin. What we want to do is move the CSS downloads to the left, so all rendering starts (and finishes!) sooner. So all you do it take the URLs of these two files and add them to .htaccess with H2PushResource in front. For me that means the URL to my custom theme's CSS /wp-content/themes/phpied2/style.css as well as some WordPress CSS stuff. While I was there I also added a JavaScript file which is loaded later. Why now start early? So the end result is:

      WordPress tip to start loading some CSS and JS files earlier.

      Sample code to add to .htaccess: H2PushResource /wp-content/themes/phpied2/style.css H2PushResource /wp-includes/css/dist/block-library/style.min.css?ver=5.4.1 H2PushResource /wp-includes/js/wp-emoji-release.min.js?ver=5.4.1

  6. Jun 2022
    1. The dataset read-only property of the HTMLElement interface provides read/write access to custom data attributes (data-*) on elements. It exposes a map of strings (DOMStringMap) with an entry for each data-* attribute.


      <div id="user" data-id="1234567890" data-user="johndoe" data-date-of-birth>John Doe</div>


      ```js const el = document.querySelector('#user');

      // el.id === 'user' // el.dataset.id === '1234567890' // el.dataset.user === 'johndoe' // el.dataset.dateOfBirth === ''

      // set a data attribute el.dataset.dateOfBirth = '1960-10-03'; // Result on JS: el.dataset.dateOfBirth === '1960-10-03' // Result on HTML: <div id="user" data-id="1234567890" data-user="johndoe" data-date-of-birth="1960-10-03">John Doe</div>

      delete el.dataset.dateOfBirth; // Result on JS: el.dataset.dateOfBirth === undefined // Result on HTML: <div id="user" data-id="1234567890" data-user="johndoe">John Doe</div>

      if ('someDataAttr' in el.dataset === false) { el.dataset.someDataAttr = 'mydata'; // Result on JS: 'someDataAttr' in el.dataset === true // Result on HTML: <div id="user" data-id="1234567890" data-user="johndoe" data-some-data-attr="mydata">John Doe</div> } ```

    1. Using the download attribute to save a <canvas> as a PNGTo save a <canvas> element's contents as an image, you can create a link with a download attribute and the canvas data as a data: URL: Example painting app with save link


      Paint by holding down the mouse button and moving it. Download my painting

      <canvas width="300" height="300"></canvas>


      css html { font-family: sans-serif; } canvas { background: #fff; border: 1px dashed; } a { display: inline-block; background: #69c; color: #fff; padding: 5px 10px; }

      ```js var canvas = document.querySelector('canvas'), c = canvas.getContext('2d'); c.fillStyle = 'hotpink';

      function draw(x, y) { if (isDrawing) { c.beginPath(); c.arc(x, y, 10, 0, Math.PI*2); c.closePath(); c.fill(); } }

      canvas.addEventListener('mousemove', event => draw(event.offsetX, event.offsetY) ); canvas.addEventListener('mousedown', () => isDrawing = true); canvas.addEventListener('mouseup', () => isDrawing = false);

      document.querySelector('a').addEventListener('click', event => event.target.href = canvas.toDataURL() ); ```

    1. Highlight part of an element This example uses the Range.setStart() and Range.setEnd() methods to add part of an address to a range. The selected range is then highlighted using Range.surroundContents(). The address contains nine nodes: five text nodes, and four <br> elements.


      Wyatt Earp<br> 101 E. Main St.<br> Dodge City, KS<br> 67801<br> USA

      Nodes in the original address:


        ```js const address = document.getElementById('address'); const log = document.getElementById('log');

        // Log info address.childNodes.forEach(node => { const li = document.createElement('li'); li.textContent = ${node.nodeName}, ${node.nodeValue}; log.appendChild(li); });

        // Highlight the street and city const startOffset = 2; // Start at third node: 101 E. Main St. const endOffset = 5; // End at fifth node: Dodge City, KS const range = document.createRange(); range.setStart(address, startOffset); range.setEnd(address, endOffset);

        const mark = document.createElement('mark'); range.surroundContents(mark); ```

      1. ```js import DOMPurify from 'dompurify'

        const App = () => { const data = lorem <b onmouseover="alert('mouseover');">ipsum</b> const sanitizedData = () => ({ __html: DOMPurify.sanitize(data) })

        return ( <div dangerouslySetInnerHTML={sanitizedData()} /> ); }

        export default App; ```

    2. May 2022
      1. ```html

        Choose your monster's colors:

        <div> <input type="color" id="head" name="head" value="#e66465"> <label for="head">Head</label> </div> <div> <input type="color" id="body" name="body" value="#f6b73c"> <label for="body">Body</label> </div>


        ```js colorPicker.addEventListener("input", updateFirst, false); colorPicker.addEventListener("change", watchColorPicker, false);

        function watchColorPicker(event) { document.querySelectorAll("p").forEach(function(p) { p.style.color = event.target.value; }); } ```

      1. Following the newer definition, the aside element should be inside of the section element to which it is related. The main element is not a sectioning element (elements like article, section, body, figure etc. are). You can of course still place aside in main, but it will be related to the nearest sectioning element parent of main. That means there is no semantic difference (for aside) in these two examples:


        <body> <main></main> <aside></aside> </body> <body> <main> <aside></aside> </main> </body>


      1. css html, body { height: 100%; margin: 0; } .wrapper { height: 100%; display: flex; flex-direction: column; } .header, .footer { background: silver; } .content { flex: 1; overflow: auto; background: pink; }


        <div class="wrapper"> <div class="header">Header</div> <div class="content"> <div style="height:1000px;">Content</div> </div> <div class="footer">Footer</div> </div>


      1. Differences from innerHTML Element.innerHTML returns HTML, as its name indicates. Sometimes people use innerHTML to retrieve or write text inside an element, but textContent has better performance because its value is not parsed as HTML. Moreover, using textContent can prevent XSS attacks.
      2. Differences from innerText Don't get confused by the differences between Node.textContent and HTMLElement.innerText. Although the names seem similar, there are important differences: textContent gets the content of all elements, including <script> and <style> elements. In contrast, innerText only shows "human-readable" elements. textContent returns every element in the node. In contrast, innerText is aware of styling and won't return the text of "hidden" elements. Moreover, since innerText takes CSS styles into account, reading the value of innerText triggers a reflow to ensure up-to-date computed styles. (Reflows can be computationally expensive, and thus should be avoided when possible.) Both textContent and innerText remove child nodes when altered, but altering innerText in Internet Explorer (version 11 and below) also permanently destroys all descendant text nodes. It is impossible to insert the nodes again into any other element or into the same element after doing so.
      1. Summary of Attributes

        • about: Specifies the subject of a relationship. If not given, then the subject is the current document.

        • rel : Defines a relation between the subject and a URL given by either href or resource. The subject is either specified by the closest about or src attribute, @@

        • rev : The same as the the rel attribute, except that subject and object are reversed.

        • property : Defines a relationship between the subject and either a string (if the content attribute is present) or a piece of markup otherwise (the content of the element that the property attribute is on).

        • content : Specifies a string to use as an object for the property attribute

        • href : Specifies an object URI for the rev and rel attributes. <mark>Takes precedence over the resource attribute</mark>.

        • resource : Specifies an object URI for the rev and rel attributes if href is not present.

        • src : Specifies the subject of a relationship.

        • datatype : Specifies a datatype of the object of the property attribute (either in the content attribute, or the content of the element that the datattype attribute is on.) By default, data in the content attribute is of type string, and data in the content of an element has type xml:Literal. If datatype="" is used, then for the RDF the element content is stripped of markup, and is of type string.

        • typeof : Creates a blank node, which becomes the subject, and asserts that the current element contains relationships that match the given RDF type.

      1. The simplest way to publish a description of your dataset is to publish DCAT metadata using RDFa. RDFa allows machine-readable metadata to be embedded in a webpage. This means that publishing your dataset metadata can be easily achieved by updating the HTML for your dataset homepage.


        <html prefix="dct: http://purl.org/dc/terms/ rdf: http://www.w3.org/1999/02/22-rdf-syntax-ns# dcat: http://www.w3.org/ns/dcat# foaf: http://xmlns.com/foaf/0.1/"> <head> <title>DCAT in RDFa</title> </head> <br /> <body> <div typeof="dcat:Dataset" resource="http://gov.example.org/dataset/finances">

        Example DCAT Dataset

        25th October 2010

        10th March 2013

        This is the description.

        <div property="dct:license" resource="http://reference.data.gov.uk/id/open-government-licence"> <span property="dct:title">UK Open Government Licence (OGL)</span> </div> <div property="dct:publisher" resource="http://example.org/publisher"> <span property="foaf:name">Example Publisher</span> </div> <div> <span property="dcat:keyword">Examples</span>, <span property="dcat:keyword">DCAT</span> </div> <div> Weekly </div> <div property='dcat:distribution' typeof='dcat:Distribution'> <span property="dct:title">CSV download</span>

        • Format <span content='text/csv' property='dcat:mediaType'>CSV</span>
        • Size <span content='240585277' datatype='xsd:decimal' property='dcat:byteSize'>1024MB</span>
        • Issues <span property='dct:issued'>2012-01-01</span>

        Download the full dataset

        </div> </body>

        </html> ```

    3. Apr 2022