Browser polyfill
Author: s | 2025-04-23
Polyfill-js.cn is a service which accepts a request for a set of browser features and returns only the polyfills that are needed by the requesting browser. Polyfill-js.cn Polyfill JS CDN Browser polyfill for making React Native compatible with web libs like pixi.js, three.js, phaser.js - browser-polyfill/ at master expo/browser-polyfill
browser-polyfill/ at master expo/browser-polyfill - GitHub
Prevent injection attacks.Avoid XSS vulnerabilities. Stored data could be vulnerable to XSS if output directly to the page. Encode any output from web storage.Through following security best practices, developers can safely leverage the benefits of web storage while mitigating risks. Being mindful of the client-side nature of web storage is critical.Browser SupportThe browser support for Web Storage APIs is generally good across modern browsers. Here are some key details:Session Storage and Local Storage have broad support in all primary desktop and mobile browsers, including Chrome, Firefox, Safari, Edge, and Opera. Cookies have near-universal support across major browsers.IndexedDB has good support across most modern browsers but lacks support in older browsers like IE10 and below.To handle limited browser support, polyfills and fallbacks can be implemented:LocalForage provides an IndexedDB polyfill that falls back to WebSQL and LocalStorage.A common fallback for SessionStorage is storing data in memory on the client side.Cookies can be a fallback for LocalStorage when browser support is limited.Web Storage enjoys broad support across browsers, but fallbacks should be implemented for maximum compatibility. The right polyfill brings IndexedDB support to older browsers. Cookies remain a tried and true storage mechanism with near-universal backing.ConclusionWeb storage is helpful in many common scenarios like storing user preferences, caching data to improve performance, and persisting data when offline. The Web Storage API provides simple synchronous key-value storage through localStorage and sessionStorage objects.When using web storage, it's essential to be mindful of browser support, security implications, and storage limits. Usage will likely grow as web
GitHub - dvandervlag/cross-browser-polyfill: A polyfill to make
Minimal repro repo: happens with both v0.2.1 on npm and when built from commit 2537b23.SummaryIf a browser.runtime.onMessage callback does not return a Promise, browser.runtime.sendMessage will be rejected with the following error, causing noise in the console:"The message port closed before a response was received."WorkaroundEven if you don't want to send a response, always return a promisein your onMessage callback: { console.log("background: onMessage", message); // Add this line: return Promise.resolve("Dummy response to keep the console quiet");});">// background.jsbrowser.runtime.onMessage.addListener(message => { console.log("background: onMessage", message); // Add this line: return Promise.resolve("Dummy response to keep the console quiet");});You can also make the onMessage callback async to implicitly return a Promise (resolving to undefined in the below example). { console.log("background: onMessage", message);});">// background.js// Notice the `async` keyword.browser.runtime.onMessage.addListener(async message => { console.log("background: onMessage", message);});FilesCopied over for convenience from: ], "js": [ "browser-polyfill-master.js", "content.js" ] } ]}">{ "manifest_version": 2, "version": "0.0.0", "name": "Test", "background": { "scripts": [ "browser-polyfill-npm.js", "background.js" ] }, "content_scripts": [ { "matches": [ "" ], "js": [ "browser-polyfill-master.js", "content.js" ] } ]}// background.jsbrowser.runtime.onMessage.addListener(onMessage);function onMessage(message) { console.log("background: onMessage", message); // 1: Causes the following to be logged in content: // "The message port closed before a response was received." return undefined; // 2: Causes this response to be logged in content, as expected. // return Promise.resolve("response from background"); // 3: Causes this error to be logged in content, as expected. // return Promise.reject(new Error("Could not respond")); // 4: Causes nothing at all to be logged in content! // I guess it is waiting for the deprecated `sendResponse` parameter to be // called. // return true;} {// console.log("content: callback", response, chrome.runtime.lastError);// });// console.log(// "content: after chrome.runtime.sendMessage with callback",// chrome.runtime.lastError// );">// content.js// 1: Unless background returns a Promise in its onMessage, this promise is// rejected with:// "The message port closed before a response was received."browser.runtime .sendMessage("hello from content") .then(console.log, console.error);// 2: This does not seem to cause any errors:// chrome.runtime.sendMessage("hello from content");// console.log("content: after chrome.runtime.sendMessage", chrome.runtime.lastError);// 3: Inside the callback, `chrome.runtime.lastError` will be:// "The message port closed before a response was received."// It seems like if `sendMessage` defines a callback but the other end doesn't// respond, Chrome is treating that as an error. Which makes sense.// The question is how this should be handled in a Promise based API.// chrome.runtime.sendMessage("hello from content", response => {// console.log("content: callback", response, chrome.runtime.lastError);// });// console.log(// "content: after chrome.runtime.sendMessage with callback",// chrome.runtime.lastError// );Solution?Should the "The message port closed before a response was received." be detected, and the promise should be resolved with undefined?GitHub - DavidAnson/math-random-polyfill: A browser-based polyfill
Browser Support Browser SupportAs a general rule of thumb, Bolt supports the last 3 major versions of desktop and mobile browsers, IE 11, and/or browsers seeing 1% or greater user traffic. Desktop Browsers Mobile Browsers Last 3 Major Versions Specific Versions IE 11 — More specifically, we use Browserslist along with shipping a codified version of the browser support stats mentioned above with our front-end development environment and tooling (ex. Autoprefixer, Babel, Eslint, and PostCSS). This allows us to automatically include or omit code based on how the latest browser stats change over time.See Below for the latest Browserslist StatsWeb Component Powered Design SystemMost of the components shipping in Bolt are built using Web Components that run natively (or near-natively, via polyfills) in all widely supported modern web browsers — including IE 11 and up.What are Web Components?According to MDN, “Web Components is a suite of different technologies allowing you to create reusable custom user interface components — with their functionality encapsulated away from the rest of your code — and utilize them in your web apps.”Think of this as a cross-browser way to define and create new native-like UI Components and interfaces, similar to how browsers have built-in UIs for the and elements....What About Cross Browser Support of Web Components?It's actually quite good!As of late February 2018, the 3** main technologies that power Web Components see native browser support at around 74% or higher -- Firefox 59 in fact is switching on support for Custom Elements on March 13th, 2018!For browsers yet to have full support for Web Components, Bolt also ships with a small polyfill loader that automatically polyfills based on the browser-specific features supported. This allows developers use Web Components seamlessly and with little performance overhead to boot.With the help of these polyfills, Bolt's cross browser support. Polyfill-js.cn is a service which accepts a request for a set of browser features and returns only the polyfills that are needed by the requesting browser. Polyfill-js.cn Polyfill JS CDNEternal Polyfilling of the Legacy Browser
Date-fns-tzTime zone support for date-fns v2.0.0 using theIntl API. By usingthe browser API no time zone data needs to be included in code bundles. Modern browsers all support thenecessary features,and for those that don't a polyfill can be used.If you do not wish to use a polyfill the time zone option can still be used, but only withtime zone offsets such as '-0200' or '+04:00' and not IANA time zone names.Table of ContentsOverviewTime Zone HelperszonedTimeToUtc - Given a date and any time zone, returns a Date with the equivalent UTC timeutcToZonedTime - Get a date/time representing local time in a given time zone from the UTC dategetTimezoneOffset - Gets the offset in milliseconds between the time zone and UTC timeTime Zone Formattingformat - Extends date-fns/format with full time zone supporttoDate - Can be used to create a zoned Date from a string containing an offset or IANA time zoneUsage with Node.jsOverviewWorking with UTC or ISO date strings is easy, and so is working with JS dates when all timesare displayed in a user's local time in the browser. The difficulty comes when working with anothertime zone's local time, other than the current system's, like on a Node server or when showing the timeof an event in a specific time zone, like an event in LA at 8pm PST regardless of where a user resides.In this case there are two relevant pieces of information:a fixed moment in time in the form of a timestamp, UTC or ISO date string, andthe time zone descriptor, usually an offset or IANA time zone name (e.g. America/New_York).Libraries like Moment and Luxon, which provide their own date time classes, manage these timestamp and timezone values internally. Since date-fns always returns a plain JS Date, which implicitly has the currentsystem's time zone, helper functions are provided forBrowser Polyfill for Babel - GitHub
That customElement.__proto__.__proto__.constructor is HTMLElementPrototype and that the prototype chain isn't modified by the polyfills(onto ElementPrototype, etc.)Contenteditable elements do not trigger MutationObserver Using the MutationObserver polyfill, it isn't possible to monitor mutations of an element marked contenteditable.See the mailing listShadowCSS: :host-context(...):host(...) doesn't work See #16 for background.Under the shadow DOM polyfill, rules like::host-context(.foo):host(.bar) {...}don't work, despite working under native Shadow DOM. The solution is to use polyfill-next-selector like:polyfill-next-selector { content: '.foo :host.bar, :host.foo.bar'; }ShadowCSS: :host(.zot:not(.bar:nth-child(2))) doesn't work ShadowCSS :host() rules can only have (at most) 1-level of nested parentheses in its argument selector under ShadowCSS. For example, :host(.zot) and :host(.zot:not(.bar)) both work, but :host(.zot:not(.bar:nth-child(2))) does not.HTML imports: document.currentScript doesn't work as expected In native HTML Imports, document.currentScript.ownerDocument references the import document itself. In the polyfill use document._currentScript.ownerDocument (note the underscore).execCommand and contenteditable isn't supported under Shadow DOM See #212execCommand, and contenteditable aren't supported under the ShadowDOM polyfill, with commands that insert or remove nodes being especially prone to failure. --> Additional resources In this articleObject.assign() browser polyfill GitHub
With viewportUnitsBuggyfill.init({hacks: window.viewportUnitsBuggyfillHacks});) and adding the viewport-units-buggyfill.hacks.js to the page after viewport-units-buggyfill.js..box { top: calc(50vh - 100px); left: calc(50vw - 100px); content: 'use_css_content_hack: true; top: calc(50vh - 100px); left: calc(50vw - 100px);';}Using the above hack one can also add support for vmax support in Safari for the older iOS6Adds support for viewport units inside of IE's filter property (a.k.a. Visual Filters).Added debounce initialization parameter, if it is desirable to not have IE9+ fire the polyfill so many times on a resize event.0.3.1 (April 16th 2014)fixing browser detection to include UIWebView - Issue #7, tylerstalder0.3.0 (April 9th 2014)fixing cross origin resource problem with CSSOM - Issue #60.2.3 (March 10th 2014)fixing multiple competing media-attribute-switched stylesheets - Issue #5fixing double initialization and call of reresh() without being initialized - Issue #3fixing s caused by innerText by using textContent instead0.2.2 (January 31st 2014)fixing unhandled empty elements - Issue #20.2.1 (January 25th 2014)adding force option to init()fixing the handling of non-iterable CSSRules - Issue #10.2.0 (January 24th 2014)optimizing generated CSS (by grouping selectors)adding browser sniffing0.1.0 (January 23rd 2014)Initial VersionLicenseviewport-unit-buggyfill is published under the MIT License.. Polyfill-js.cn is a service which accepts a request for a set of browser features and returns only the polyfills that are needed by the requesting browser. Polyfill-js.cn Polyfill JS CDNComments
Prevent injection attacks.Avoid XSS vulnerabilities. Stored data could be vulnerable to XSS if output directly to the page. Encode any output from web storage.Through following security best practices, developers can safely leverage the benefits of web storage while mitigating risks. Being mindful of the client-side nature of web storage is critical.Browser SupportThe browser support for Web Storage APIs is generally good across modern browsers. Here are some key details:Session Storage and Local Storage have broad support in all primary desktop and mobile browsers, including Chrome, Firefox, Safari, Edge, and Opera. Cookies have near-universal support across major browsers.IndexedDB has good support across most modern browsers but lacks support in older browsers like IE10 and below.To handle limited browser support, polyfills and fallbacks can be implemented:LocalForage provides an IndexedDB polyfill that falls back to WebSQL and LocalStorage.A common fallback for SessionStorage is storing data in memory on the client side.Cookies can be a fallback for LocalStorage when browser support is limited.Web Storage enjoys broad support across browsers, but fallbacks should be implemented for maximum compatibility. The right polyfill brings IndexedDB support to older browsers. Cookies remain a tried and true storage mechanism with near-universal backing.ConclusionWeb storage is helpful in many common scenarios like storing user preferences, caching data to improve performance, and persisting data when offline. The Web Storage API provides simple synchronous key-value storage through localStorage and sessionStorage objects.When using web storage, it's essential to be mindful of browser support, security implications, and storage limits. Usage will likely grow as web
2025-04-13Minimal repro repo: happens with both v0.2.1 on npm and when built from commit 2537b23.SummaryIf a browser.runtime.onMessage callback does not return a Promise, browser.runtime.sendMessage will be rejected with the following error, causing noise in the console:"The message port closed before a response was received."WorkaroundEven if you don't want to send a response, always return a promisein your onMessage callback: { console.log("background: onMessage", message); // Add this line: return Promise.resolve("Dummy response to keep the console quiet");});">// background.jsbrowser.runtime.onMessage.addListener(message => { console.log("background: onMessage", message); // Add this line: return Promise.resolve("Dummy response to keep the console quiet");});You can also make the onMessage callback async to implicitly return a Promise (resolving to undefined in the below example). { console.log("background: onMessage", message);});">// background.js// Notice the `async` keyword.browser.runtime.onMessage.addListener(async message => { console.log("background: onMessage", message);});FilesCopied over for convenience from: ], "js": [ "browser-polyfill-master.js", "content.js" ] } ]}">{ "manifest_version": 2, "version": "0.0.0", "name": "Test", "background": { "scripts": [ "browser-polyfill-npm.js", "background.js" ] }, "content_scripts": [ { "matches": [ "" ], "js": [ "browser-polyfill-master.js", "content.js" ] } ]}// background.jsbrowser.runtime.onMessage.addListener(onMessage);function onMessage(message) { console.log("background: onMessage", message); // 1: Causes the following to be logged in content: // "The message port closed before a response was received." return undefined; // 2: Causes this response to be logged in content, as expected. // return Promise.resolve("response from background"); // 3: Causes this error to be logged in content, as expected. // return Promise.reject(new Error("Could not respond")); // 4: Causes nothing at all to be logged in content! // I guess it is waiting for the deprecated `sendResponse` parameter to be // called. // return true;} {// console.log("content: callback", response, chrome.runtime.lastError);// });// console.log(// "content: after chrome.runtime.sendMessage with callback",// chrome.runtime.lastError// );">// content.js// 1: Unless background returns a Promise in its onMessage, this promise is// rejected with:// "The message port closed before a response was received."browser.runtime .sendMessage("hello from content") .then(console.log, console.error);// 2: This does not seem to cause any errors:// chrome.runtime.sendMessage("hello from content");// console.log("content: after chrome.runtime.sendMessage", chrome.runtime.lastError);// 3: Inside the callback, `chrome.runtime.lastError` will be:// "The message port closed before a response was received."// It seems like if `sendMessage` defines a callback but the other end doesn't// respond, Chrome is treating that as an error. Which makes sense.// The question is how this should be handled in a Promise based API.// chrome.runtime.sendMessage("hello from content", response => {// console.log("content: callback", response, chrome.runtime.lastError);// });// console.log(// "content: after chrome.runtime.sendMessage with callback",// chrome.runtime.lastError// );Solution?Should the "The message port closed before a response was received." be detected, and the promise should be resolved with undefined?
2025-03-25Date-fns-tzTime zone support for date-fns v2.0.0 using theIntl API. By usingthe browser API no time zone data needs to be included in code bundles. Modern browsers all support thenecessary features,and for those that don't a polyfill can be used.If you do not wish to use a polyfill the time zone option can still be used, but only withtime zone offsets such as '-0200' or '+04:00' and not IANA time zone names.Table of ContentsOverviewTime Zone HelperszonedTimeToUtc - Given a date and any time zone, returns a Date with the equivalent UTC timeutcToZonedTime - Get a date/time representing local time in a given time zone from the UTC dategetTimezoneOffset - Gets the offset in milliseconds between the time zone and UTC timeTime Zone Formattingformat - Extends date-fns/format with full time zone supporttoDate - Can be used to create a zoned Date from a string containing an offset or IANA time zoneUsage with Node.jsOverviewWorking with UTC or ISO date strings is easy, and so is working with JS dates when all timesare displayed in a user's local time in the browser. The difficulty comes when working with anothertime zone's local time, other than the current system's, like on a Node server or when showing the timeof an event in a specific time zone, like an event in LA at 8pm PST regardless of where a user resides.In this case there are two relevant pieces of information:a fixed moment in time in the form of a timestamp, UTC or ISO date string, andthe time zone descriptor, usually an offset or IANA time zone name (e.g. America/New_York).Libraries like Moment and Luxon, which provide their own date time classes, manage these timestamp and timezone values internally. Since date-fns always returns a plain JS Date, which implicitly has the currentsystem's time zone, helper functions are provided for
2025-04-05That customElement.__proto__.__proto__.constructor is HTMLElementPrototype and that the prototype chain isn't modified by the polyfills(onto ElementPrototype, etc.)Contenteditable elements do not trigger MutationObserver Using the MutationObserver polyfill, it isn't possible to monitor mutations of an element marked contenteditable.See the mailing listShadowCSS: :host-context(...):host(...) doesn't work See #16 for background.Under the shadow DOM polyfill, rules like::host-context(.foo):host(.bar) {...}don't work, despite working under native Shadow DOM. The solution is to use polyfill-next-selector like:polyfill-next-selector { content: '.foo :host.bar, :host.foo.bar'; }ShadowCSS: :host(.zot:not(.bar:nth-child(2))) doesn't work ShadowCSS :host() rules can only have (at most) 1-level of nested parentheses in its argument selector under ShadowCSS. For example, :host(.zot) and :host(.zot:not(.bar)) both work, but :host(.zot:not(.bar:nth-child(2))) does not.HTML imports: document.currentScript doesn't work as expected In native HTML Imports, document.currentScript.ownerDocument references the import document itself. In the polyfill use document._currentScript.ownerDocument (note the underscore).execCommand and contenteditable isn't supported under Shadow DOM See #212execCommand, and contenteditable aren't supported under the ShadowDOM polyfill, with commands that insert or remove nodes being especially prone to failure. --> Additional resources In this article
2025-04-03Canvas 5 PolyfillCanvas 5 Polyfill is a Javascript polyfill library to fill in new features for HTML 5Canvas that browsers may not have implemented yet, such as Path2D objects andellipse() on CanvasRenderingContext2D.InstallationCanvas 5 Polyfill uses Bower to make installation easy: bower install --save canvas-5-polyfillYou can also get the code directly at GitHub.Usage Test Canvas Polyfill var ctx = document.getElementById('ID').getContext('2d'); var p = new Path2D(); p.moveTo(100, 10); p.lineTo(10, 100); ctx.strokeStyle = '#555'; ctx.lineWidth = 10; ctx.stroke(p); "> Test Canvas Polyfill var ctx = document.getElementById('ID').getContext('2d'); var p = new Path2D(); p.moveTo(100, 10); p.lineTo(10, 100); ctx.strokeStyle = '#555'; ctx.lineWidth = 10; ctx.stroke(p); StatusCanvas 5 Polyfill adds the following classes and methods to an existing HTMLCanvas implementation if they are missing, if they are not missing the nativeimplementations are used:The polyfill adds the following methods to CanvasRenderingContext2D:void stroke(Path2D path);void fill(Path2D path, optional CanvasFillRule fillRule = "nonzero");void clip(Path2D path, optional CanvasFillRule fillRule = "nonzero");boolean isPointInPath(Path2D path, double x, double y, optional CanvasFillRule fillRule = "nonzero");boolean isPointInStroke(Path2D path, double x, double y);void ellipse( double x, double y, double radiusX, double radiusY, double rotation, double startAngle, double endAngle, optional boolean anticlockwise = false);It also adds Path2D with the following constructors:Path2D()Path2D(Path2D path, optional CanvasFillRule fillRule = "nonzero"),Path2D(DOMString d)Where Path2D has the following methods:void addPath(Path2D path, SVGMatrix? transformation);void closePath();void moveTo(double x, double y);void lineTo(double x, double y);void quadraticCurveTo( double cpx, double cpy, double x, double y);void bezierCurveTo( double cp1x, double cp1y, double cp2x, double cp2y, double x, double y);void arcTo(double x1, double y1, double x2, double y2, double radius);void arcTo(double x1, double y1, double x2, double y2, double radiusX, double radiusY, double rotation);void rect(double x, double y, double w, double h);void arc(double x, double y, double radius, double startAngle, double endAngle, optional boolean anticlockwise = false);void ellipse(double x, double y, double radiusX, double radiusY, double rotation, double startAngle, double
2025-04-11CSS files. });You can find sample implementations in our test directory.TestingDue to CSP restrictions and our CSS parser there’s no way to test this polyfill from a filesystem. You need to set up a local server that serves from root directory. Calling should work then. php -S localhost:8000 for example would start a local PHP server on your current directory.DOM watching capabilitiesIn browsers greater IE8 the polyfill uses DOM Mutation Events or Mutation Observers (depending on what's available) to detect the injection of further images matching the defined selector. This means that it will also apply itself to any images that you append to the DOM at any later point. And it will detach itself from images that you remove from the DOM. Since this feature is sort of complicated to craft in a rock solid way, you might look out for unexpected behaviors.Security / Mixed Content Issues and 3rd Party CSSIf you use any third party CSS or mixed content on your website (Webfonts from a service, a CDN, or similar), the polyfill might not work as expected.You can still use the polyfill but then need to set some options regarding CSP:For example you need to set the header to:'Access-Control-Allow-Origin: *'This should fix the issue. If you also need to support credentials, you can’t use * but need the server reply with two headers (server needs also to reply with Access-Control-Allow-Credentials: true), one of which includes the origin in question.It is recommended to add the attribute crossorigin="" to your CSS link element that is called from the external resource to indicate what type of CORS the server should reply with.In case you can’t alter the CSP / CORS settings of the server in question, you can disable parsing external CSS files in the config of the call: objectFit.polyfill({ selector: 'img', fittype: 'cover', disableCrossDomain: 'true' });AuthorThis polyfill is written by Anselm Hannemann and Christian "Schepp" Schaefer. Follow them on Twitter via @helloanselm and @derSchepp or check their GitHub profiles via anselmh and Schepp for more information.LicenseThis project is under the MIT Open Source License. See the LICENSE file for more information.
2025-03-31