The error
The error + your comment about not needing to change the context signifies that you're probably not actually injecting in a regular webpage that runs content scripts, but into an extension page (with visible URL chrome-extension://...
).
Anything in such a page is not a content script by definition. Even if that code is also shared with a content script used somewhere else.
Note that if you're using (but not showing) allFrames: true
for injection, you may be accidentally injecting in an extension-page frame, leading to that error.
Non-content script code
The problem is that you can't declare host permissions for chrome-extension://
pages. Therefore you can't inject content scripts into those pages.
It's not possible to define permissions to do that from an extension alone (to make an extension you can distribute that "just works"), but you can do it locally with Chrome flags + chrome.debugger
API.
You will need chrome://flags/#silent-debugger-extension-api
enabled and will need to use the Debugger Protocol to execute your code.
Sadly, the chrome://flags/#extensions-on-chrome-urls
flag does not allow injection into this protocol either, so you have to use Debugger.
Content script code
If you're actually trying to reach code in a content script in a regular webpage, you can't call it from your own content script because every extension gets its own isolated JS context.
You'd need chrome.debugger
again.
Code injected in the page context
Sometimes you're dealing with code that's injected in the webpage itself from a content script.
Then you should be able to access it with the method you describe by making the same content script -> page code leap. See the link above.
That doesn't explain the error you're getting though.