Luke Shining
Luke Shining

Reputation: 19

What's the difference between Chrome console and in-page javascript?

This JavaScript statement WAS valid in previous Chrome versions(as part of a Chrome extension content.js) in 5 months ago:

require(["function-widget-1:share/util/service/createLinkShare.js"]).prototype.makePrivatePassword=function(){return prompt("Some Massage:","")};

But now (in latest Chrome, as part of a Chrome extension content.js) it is invalid and the error massage is "Uncaught ReferenceError: require is not defined".

However, it is now (in latest Chrome) still valid if I type the same statement into the Chrome console (as in Developer Tools).

So my question is: What made the difference between the two scenarios?

Upvotes: 1

Views: 657

Answers (1)

Xan
Xan

Reputation: 77523

What you're seeing is called "Isolated world":

Content scripts execute in a special environment called an isolated world. They have access to the DOM of the page they are injected into, but not to any JavaScript variables or functions created by the page. It looks to each content script as if there is no other JavaScript executing on the page it is running on. The same is true in reverse: JavaScript running on the page cannot call any functions or access any variables defined by content scripts.

Essentially, content scripts run in a completely separate JS context (think "virtual machine") attached to the same DOM tree and don't see each other's code.

When using the Dev Tools console, you can switch JS contexts with a drop-down above it (initially says "top"). It should list already present content script contexts.

It is possible to cross the boundary and have some code running in the page's own context; this technique is colloquially called "injected scripts" (not to be confused with programmatic injection of content scripts) or "page-level scripts" and are canonically covered by this question.

However, any code that crosses this boundary becomes hard to communicate with - as it becomes indistinguishable from the page's own code, which is, as noted, is invisible to content scripts. A couple of questions that cover this: with content script, with background.

Upvotes: 1

Related Questions