Skip to content
Advertisement

Loading external javascript in google chrome extension

I’m writing a Google Chrome extension which manipulates the current page (basically adds a button).

In my content script, I want to load the Facebook Graph API:

JavaScript

However, the script doesn’t seem to added to body. Here’s the console log:

JavaScript

Any ideas on what I’m doing wrong?

Advertisement

Answer

The issue is that the JavaScript inside the content scripts runs in its own sandboxed environment and only has access to other JavaScript that was loaded in one of two ways:

Via the manifest:

JavaScript

Or using Programmatic injection:

JavaScript

Be sure to update your manifest permissions:

JavaScript

Appending a script tag will in effect evaluate the JavaScript in the context of the containing page, outside of the JavaScript sandbox that your JavaScript has access to.

Also, since the FB script requires the “fb-root” to be in the DOM, you will probably need to use the programmatic approach so that you can first update the DOM with the element, then pass a message back to the background page to load the Facebook script so it is accessible to the JavaScript that is loaded in the content scripts.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement