I asked blackbox.ai
to generate a usercript that would create a polyfill for Array.prototype.findLast
.
This method is defined in modern javascript, but may be missing on older browsers.
I tested with an old browser.
I can see the console.log
messages, which means the script is executed.
Nevertheless, when I execute Array.prototype.findLast
in the console it says undefined
.
Here's the userscript:
// ==UserScript==
// @name Array.prototype.findLast Polyfill
// @author ychaouche
// @namespace ychaouche.scripts
// @version 2024-11-04
// @description Add findLast method to Array.prototype if it doesn't exist
// @match *://*/*
// ==/UserScript==
(function() {
'use strict';
if (!Array.prototype.findLast) {
Array.prototype.findLast = function(callback, thisArg) {
if (this == null) {
throw new TypeError('Array.prototype.findLast called on null or undefined');
}
if (typeof callback !== 'function') {
throw new TypeError('callback must be a function');
}
const list = Object(this);
const length = list.length >>> 0;
for (let i = length - 1; i >= 0; i--) {
if (i in list) {
const element = list[i];
if (callback.call(thisArg, element, i, list)) {
return element;
}
}
}
return undefined;
};
console.log('Array.prototype.findLast polyfill has been added.');
} else {
console.log('Array.prototype.findLast already exists.');
}
// Optional: Test the polyfill
var testArray = [1, 2, 3, 4, 5];
var lastEven = testArray.findLast(num => num % 2 === 0);
console.log('Last even number:', lastEven);
})();
Here's the console trace showing the console.log
messages, as well as an undefined
when I try to access Array.prototype.findLast
myself after the page loads:
Array.prototype.findLast polyfill has been added. Array.prototype.findLast-Polyfill.user.js:37:17
Last even number: 4
>> Array.prototype.findLast
undefined
The problem wasn't the script itself,
it was the CSP policy of the website I was visiting.
The script worked well on another website.
I am using firefox,
and it seems you can't disable CSP for a particular website or tab in firefox.