Why do functions and classes assigned to `window` not equal themselves in a GreaseMonkey script?
Asked Answered
B

0

6

I have a class Foo with a static method that compares this to Foo, and for some reason the output of that comparison is false:

// ==UserScript==
// @name     GreaseMonkey test
// @version  1
// @grant    none
// @include  *
// ==/UserScript==

window['Cls'] = class {};
window['func'] = function() {};

console.log(Cls === Cls);  // output: false
console.log(func === func);  // output: false

How can this be? I suspect it's related to the fact that Greasemonkey executes userscripts in a sandbox with elevated privileges, but even then I cannot understand why this would output false. Furthermore, the output changes to true if the function and the class aren't assigned to window:

class Cls {};
function func() {};

console.log(Cls === Cls);  // output: true
console.log(func === func);  // output: true

What is going on here?

Batchelor answered 14/10, 2018 at 18:28 Comment(5)
This is really weird, wow. Can you also a) try with a {} object instead of a function b) try to evaluate the comparison multiple times (may it only returns something different on first access) c) log the values before comparing them?Lillylillywhite
GM 4+ is all kinds of fubar. That's why I no longer support it. Just tell your users to use Tampermonkey or Violentmonkey, as GM itself recommends.Odle
Objects seem to behave as expected, they === each other and === the same thing on window and unsafeWindowCanzone
@BrockAdams I'm using GM 3.11, and the problem occurs there as well.Canzone
@Lillylillywhite a) {} objects compare equal to themselves. b) The result is false every time. c) logging the values yields the source code of the class/function, nothing unexpected. But I have discovered that the comparison returns true if I assign the class/function to a variable first: var f = func; f === f // trueBatchelor

© 2022 - 2024 — McMap. All rights reserved.