Skip to content

open the “closed” shadowRoot of element inserted by other extension in chrome

well google translate extension in chrome, has popup feature, it displays translation of selected word instantly, I wanted to access those translations displayed by popup, but this popup element is shadowRoot(“closed”), so javascript cant access its content, I red an article about that subject and author says:

But really there is nothing stopping someone executing the following JavaScript before your component definition. Element.prototype._attachShadow = Element.prototype.attachShadow; Element.prototype.attachShadow = function () { return this._attachShadow( { mode: "open" } ); };

Is it possible to change attachShadow method of other extension? if so where should it be executed by my extension? background_script or maybe somewhere. I think each extension has its own enviroment and I have no chane to edit their methods. I wish I’m wrong 🙂

Answer

No need to override it. Simply use this method in the content script:

let shadowRoot = chrome.dom.openOrClosedShadowRoot(element);

It’s not in the documentation, but here’s its definition in the source code: link.