From 36b2a7bc35a45dd29af10b4e19c3f72609f0cfc0 Mon Sep 17 00:00:00 2001 From: Oliver Byford Date: Mon, 10 Oct 2022 16:35:02 +0100 Subject: [PATCH] Add polyfill for `String.prototype.trim` In bc843a3 (#2840) we introduced a new `normaliseString` helper method [1] which relies on `String.prototype.trim` [2], which is not supported in IE8 or IE9 [3] This causes a script error when going to any page in the review app (in IE8) which contains a component that accepts config via data attributes. Add a polyfill for String.prototype.trim based on the polyfill that used to be on MDN [4] (before they removed content relating to IE8), adapted to match the format used for the existing polyfills. [1]: https://github.com/alphagov/govuk-frontend/blob/cf7b06ceb19236a9afeb5399158b35391219cf99/src/govuk/common.mjs#L152 [2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim [3]: https://caniuse.com/mdn-javascript_builtins_string_trim [4]: https://github.com/mdn/content/blob/cf607d68522cd35ee7670782d3ee3a361eaef2e4/files/en-us/web/javascript/reference/global_objects/string/trim/index.md#polyfill --- src/govuk/common.mjs | 1 + .../vendor/polyfills/String/prototype/trim.mjs | 13 +++++++++++++ 2 files changed, 14 insertions(+) create mode 100644 src/govuk/vendor/polyfills/String/prototype/trim.mjs diff --git a/src/govuk/common.mjs b/src/govuk/common.mjs index 08a1673f74..22f23ddd53 100644 --- a/src/govuk/common.mjs +++ b/src/govuk/common.mjs @@ -1,4 +1,5 @@ import './vendor/polyfills/Element/prototype/dataset.mjs' +import './vendor/polyfills/String/prototype/trim.mjs' /** * TODO: Ideally this would be a NodeList.prototype.forEach polyfill diff --git a/src/govuk/vendor/polyfills/String/prototype/trim.mjs b/src/govuk/vendor/polyfills/String/prototype/trim.mjs new file mode 100644 index 0000000000..ccef2420b1 --- /dev/null +++ b/src/govuk/vendor/polyfills/String/prototype/trim.mjs @@ -0,0 +1,13 @@ +(function(undefined) { + + // Detection from https://github.com/mdn/content/blob/cf607d68522cd35ee7670782d3ee3a361eaef2e4/files/en-us/web/javascript/reference/global_objects/string/trim/index.md#polyfill + var detect = ('trim' in String.prototype) + + if (detect) return + + // Polyfill from https://github.com/mdn/content/blob/cf607d68522cd35ee7670782d3ee3a361eaef2e4/files/en-us/web/javascript/reference/global_objects/string/trim/index.md#polyfill + String.prototype.trim = function () { + return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); + }; + +}).call('object' === typeof window && window || 'object' === typeof self && self || 'object' === typeof global && global || {});