getBackgroundPage instanceof

70 views
Skip to first unread message

Maksim Ivanov

unread,
Dec 3, 2021, 5:40:58 PM12/3/21
to Chromium Extensions
Hello,

The object that's returned by chrome.runtime.getBackgroundPage() gives false when called with "instanceof Window". I presume it's because the background page's Window interface is not the same as other pages' Window interfaces.

Does anyone know what's the actual type of that object, so that "instanceof <something>" can evaluate to true? Or at least how to detect inside some random function that it received another page's Window object?


Thanks,
Maksim

hrg...@gmail.com

unread,
Dec 3, 2021, 5:59:00 PM12/3/21
to Chromium Extensions, em...@chromium.org
Window objects that belong to different browsing contexts have different constructors, so you cannot use instanceof to test their type.
Instead you can do this:

Maksim Ivanov

unread,
Dec 3, 2021, 6:10:00 PM12/3/21
to hrg...@gmail.com, Chromium Extensions
Thanks for the quick response!

Is there a way to make it a bit more reliable, because I guess the ".constructor.name" approach is suspect to false positives like this:
{'constructor': {'name': 'Window'}}
or just:
{'constructor': Window}

hrg...@gmail.com

unread,
Dec 3, 2021, 7:02:26 PM12/3/21
to Chromium Extensions, em...@chromium.org, Chromium Extensions, hrg...@gmail.com
You can try something like this is you are really paranoid: 
 
bgPage.__proto__.constructor.name == "Window"

Or

bgPage.__proto__[Symbol.toStringTag] == "Window"

But keep in mind that __proto__ is deprecated.

hrg...@gmail.com

unread,
Dec 14, 2021, 5:00:10 AM12/14/21
to Chromium Extensions, hrg...@gmail.com, em...@chromium.org, Chromium Extensions
I've just realized you can also do this:
bgPage instanceof  bgPage.Window

which is what you were originally asking.

Empathic Awakened Cancerian

unread,
Dec 14, 2021, 5:06:26 AM12/14/21
to hrg...@gmail.com, Chromium Extensions, hrg...@gmail.com, em...@chromium.org, Chromium Extensions
Who said anything about being paranoid the browser is working like it is


From: chromium-...@chromium.org <chromium-...@chromium.org> on behalf of hrg...@gmail.com <hrg...@gmail.com>
Sent: Tuesday, December 14, 2021 4:00:10 AM
To: Chromium Extensions <chromium-...@chromium.org>
Cc: hrg...@gmail.com <hrg...@gmail.com>; em...@chromium.org <em...@chromium.org>; Chromium Extensions <chromium-...@chromium.org>
Subject: [crx] Re: getBackgroundPage instanceof
 
--
You received this message because you are subscribed to the Google Groups "Chromium Extensions" group.
To unsubscribe from this group and stop receiving emails from it, send an email to chromium-extens...@chromium.org.
To view this discussion on the web visit https://groups.google.com/a/chromium.org/d/msgid/chromium-extensions/625d2118-74d5-475e-8e42-4e55578ca90en%40chromium.org.
Reply all
Reply to author
Forward
0 new messages