0

I have a existing file ajax,js in my website that makes an ajax request and creates a global JSON object, searchResult using that response. Now I am creating a Chrome plugin, that requires this JSON Object inside it. I have a content script for the plugin viz. plugin.js and I want to include the object inside plugin.js file.

When I try to log window.searchResult from within plugin.js, it shows as undefined.

but when I use browser console, it shows the value as expected.

Please help me with this.

Souvik Banerjee
  • 187
  • 1
  • 3
  • 14

1 Answers1

1

Problem

Chrome content scripts and the page's own scripts live in isolated worlds.

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.

Your code works in the console, since you execute it by default in the page's context. To see what the extension sees, you need to switch it.

Solution 1a

First, the generic solution (works even if you don't control the webpage)

There is a way around this, by injecting some code directly into the page's "world" (or properly called, context).

After injecting the code, your page-level script needs to communicate with the content script to pass the data. It's possible with custom DOM events (as, as you remember, DOM is shared). The page-level script sends an event with the data in the event's details.

Alternatively, you can just attach the data to some DOM node, say, an invisible <div>.

Solution 1b

Since you said it's your page, you can skip the inject-into-the-page step and have a listener ready in the page's own code.

The content script sends a custom event to request the data, and the page answers passes the data back as described in 1a.

Solution 2

In theory, you don't even need a content script.

You can use the "externally_connectable" mechanism to speak with the page directly.

Note though that the page has to initiate the conversation.

Community
  • 1
  • 1
Xan
  • 74,770
  • 16
  • 179
  • 206