Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: [API] is undefined in content script or Why can't I do this in a content script?

I was trying to write a simple extension in Firefox wherein I modify the X-Frame-Allow header.

I looked at the documentation briefly and I see that they support webRequest.onHeadersReceived.addListener(). However, I'm unable to get my code to run when the headers are received.

manifest.json

{
  "manifest_version": 2,
  "name": "xframeoptions",
  "version": "1.0",
  "description": "Set X-Frame-Options to ALLOW",
  "icons": {
    "48": "icons/icon.png"
  },
  "permissions": [
    "webRequest",
    "webRequestBlocking",
    "<all_urls>"
  ],
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["xframeoptions.js"]
    }
  ]
}

xframeoptions.js

function rewriteHeader(e) {
  console.log(e.responseHeaders);

  for (var header of e.responseHeaders) {
    console.log(header.name + ":" + header.value);
    if (header.name == "X-Frame-Options") {
      header.value = 'ALLOW';
      modified = true;
      break;
    }
  }
  return {responseHeaders: e.responseHeaders};
}

console.log("Initializing xframeoptions extension ...test");


browser.webRequest.onHeadersReceived.addListener(
  rewriteHeader,
  {urls: ['<all_urls>']},
  ["blocking", "responseHeaders"]
);

How do I modify response headers via Firefox's WebExtensions?

like image 770
Guru Prasad Avatar asked Dec 06 '16 12:12

Guru Prasad


People also ask

What are content scripts in Chrome?

Content scripts are JavaScript files that run in the context of web pages. By using the standard Document Object Model (DOM), they can read details of the web pages the browser visits, or make changes to them.

How do I add a script to Firefox?

Loading content scripts You can load a content script into a web page in one of three ways: At install time, into pages that match URL patterns. Using the content_scripts key in your manifest. json , you can ask the browser to load a content script whenever the browser loads a page whose URL matches a given pattern.

What is the difference between content script and background script?

Background Script - Provides persistence and handles background events. Content Script - Scripts that run in isolation in the context of the web page. Injected Script - Scripts that are programmatically injected into the web page.

How do you send data from content script to popup in HTML?

The popup can contain any HTML contents that you like, and it's automatically sized to fit its contents. To add a popup to your browser action, create an HTML file with the popup's contents. Specify the HTML file in the default_popup field of browser_action in the manifest, or call the browserAction. setPopup method.


2 Answers

Content scripts do not have access the API you are using

You are attempting to do this from a content script. You need to be doing this from a background script. Content scripts have access to a small subset of the WebExtensions APIs. The available APIs include (from the MDN Content Scripts page):

From extension:

  • getURL()
  • inIncognitoContext

From runtime:

  • connect()
  • getManifest()
  • getURL()
  • onConnect
  • onMessage
  • sendMessage()

From i18n:

  • getMessage()
  • getAcceptLanguages()
  • getUILanguage()
  • detectLanguage()

Everything from storage.

This does not include the API you are trying to use (e.g. webRequest).

Change your manifest.json to use a background page

You should change your manifest.json to instead of having a content_scripts key for your xframeoptions.js, run it as a background script using something like:

"background": {
    "scripts": [
        "xframeoptions.js"
    ]
},

Extensions are separated into background scripts and content scripts

If you need the information from calling the API in your content script, you will need to use message passing to communicate between the content script and your background script. However, often you can move the complete logic to a script running in the background context (background scripts, popup scripts, options page scripts, etc.). What, exactly, will be required will depend on what you desire to accomplish with your script.

This separation of functionality between all privileged APIs being available in the background context and access to web page content available in content scripts (with very limited access to privileged APIs), with asynchronous messaging between them, is fundamental to how extensions are architected. You will need to design your extension around this architecture.

Some possible errors which might be caused by this issue

There are a number of possible errors which might be caused by this issue. The following is an incomplete list of possible errors:

TypeError: browser.alarms is undefined
TypeError: browser.bookmarks is undefined
TypeError: browser.browserAction is undefined
TypeError: browser.browsingData is undefined
TypeError: browser.commands is undefined
TypeError: browser.contextMenus is undefined
TypeError: browser.contextualIdentities is undefined
TypeError: browser.cookies is undefined
TypeError: browser.devtools.inspectedWindow is undefined
TypeError: browser.downloads is undefined
TypeError: browser.events is undefined
TypeError: browser.extension.getBackgroundPage is undefined
TypeError: browser.extension.getExtensionTabs is undefined
TypeError: browser.extension.getViews is undefined
TypeError: browser.extension.isAllowedFileSchemeAccess is undefined
TypeError: browser.extension.isAllowedIncognitoAccess is undefined
TypeError: browser.extension.lastError is undefined
TypeError: browser.extension.onRequest is undefined
TypeError: browser.extension.onRequestExternal is undefined
TypeError: browser.extension.sendRequest is undefined
TypeError: browser.extension.setUpdateUrlData is undefined
TypeError: browser.extension.ViewType is undefined
TypeError: browser.extensionTypes is undefined
TypeError: browser.history is undefined
TypeError: browser.i18n.LanguageCode is undefined
TypeError: browser.identity is undefined
TypeError: browser.idle is undefined
TypeError: browser.management is undefined
TypeError: browser.notifications is undefined
TypeError: browser.omnibox is undefined
TypeError: browser.pageAction is undefined
TypeError: browser.privacy is undefined
TypeError: browser.runtime.connectNative is undefined
TypeError: browser.runtime.getBackgroundPage is undefined
TypeError: browser.runtime.getBrowserInfo is undefined
TypeError: browser.runtime.getPackageDirectoryEntry is undefined
TypeError: browser.runtime.getPlatformInfo is undefined
TypeError: browser.runtime.id is undefined
TypeError: browser.runtime.lastError is undefined
TypeError: browser.runtime.MessageSender is undefined
TypeError: browser.runtime.onBrowserUpdateAvailable is undefined
TypeError: browser.runtime.onConnectExternal is undefined
TypeError: browser.runtime.onInstalled is undefined
TypeError: browser.runtime.OnInstalledReason is undefined
TypeError: browser.runtime.onMessageExternal is undefined
TypeError: browser.runtime.onRestartRequired is undefined
TypeError: browser.runtime.OnRestartRequiredReason is undefined
TypeError: browser.runtime.onStartup is undefined
TypeError: browser.runtime.onSuspend is undefined
TypeError: browser.runtime.onSuspendCanceled is undefined
TypeError: browser.runtime.onUpdateAvailable is undefined
TypeError: browser.runtime.openOptionsPage is undefined
TypeError: browser.runtime.PlatformArch is undefined
TypeError: browser.runtime.PlatformInfo is undefined
TypeError: browser.runtime.PlatformNaclArch is undefined
TypeError: browser.runtime.PlatformOs is undefined
TypeError: browser.runtime.Port is undefined
TypeError: browser.runtime.reload is undefined
TypeError: browser.runtime.requestUpdateCheck is undefined
TypeError: browser.runtime.RequestUpdateCheckStatus is undefined
TypeError: browser.runtime.sendNativeMessage is undefined
TypeError: browser.runtime.setUninstallURL is undefined
TypeError: browser.sessions is undefined
TypeError: browser.sidebarAction is undefined
TypeError: browser.tabs is undefined
TypeError: browser.thing is undefined
TypeError: browser.topSites is undefined
TypeError: browser.webNavigation is undefined
TypeError: browser.webRequest is undefined
TypeError: browser.windows is undefined
TypeError: chrome.alarms is undefined
TypeError: chrome.bookmarks is undefined
TypeError: chrome.browserAction is undefined
TypeError: chrome.browsingData is undefined
TypeError: chrome.commands is undefined
TypeError: chrome.contextMenus is undefined
TypeError: chrome.contextualIdentities is undefined
TypeError: chrome.cookies is undefined
TypeError: chrome.devtools.inspectedWindow is undefined
TypeError: chrome.downloads is undefined
TypeError: chrome.events is undefined
TypeError: chrome.extension.getBackgroundPage is undefined
TypeError: chrome.extension.getExtensionTabs is undefined
TypeError: chrome.extension.getViews is undefined
TypeError: chrome.extension.isAllowedFileSchemeAccess is undefined
TypeError: chrome.extension.isAllowedIncognitoAccess is undefined
TypeError: chrome.extension.lastError is undefined
TypeError: chrome.extension.onRequest is undefined
TypeError: chrome.extension.onRequestExternal is undefined
TypeError: chrome.extension.sendRequest is undefined
TypeError: chrome.extension.setUpdateUrlData is undefined
TypeError: chrome.extension.ViewType is undefined
TypeError: chrome.extensionTypes is undefined
TypeError: chrome.history is undefined
TypeError: chrome.i18n.LanguageCode is undefined
TypeError: chrome.identity is undefined
TypeError: chrome.idle is undefined
TypeError: chrome.management is undefined
TypeError: chrome.notifications is undefined
TypeError: chrome.omnibox is undefined
TypeError: chrome.pageAction is undefined
TypeError: chrome.privacy is undefined
TypeError: chrome.runtime.connectNative is undefined
TypeError: chrome.runtime.getBackgroundPage is undefined
TypeError: chrome.runtime.getBrowserInfo is undefined
TypeError: chrome.runtime.getPackageDirectoryEntry is undefined
TypeError: chrome.runtime.getPlatformInfo is undefined
TypeError: chrome.runtime.id is undefined
TypeError: chrome.runtime.lastError is undefined
TypeError: chrome.runtime.MessageSender is undefined
TypeError: chrome.runtime.onBrowserUpdateAvailable is undefined
TypeError: chrome.runtime.onConnectExternal is undefined
TypeError: chrome.runtime.onInstalled is undefined
TypeError: chrome.runtime.OnInstalledReason is undefined
TypeError: chrome.runtime.onMessageExternal is undefined
TypeError: chrome.runtime.onRestartRequired is undefined
TypeError: chrome.runtime.OnRestartRequiredReason is undefined
TypeError: chrome.runtime.onStartup is undefined
TypeError: chrome.runtime.onSuspend is undefined
TypeError: chrome.runtime.onSuspendCanceled is undefined
TypeError: chrome.runtime.onUpdateAvailable is undefined
TypeError: chrome.runtime.openOptionsPage is undefined
TypeError: chrome.runtime.PlatformArch is undefined
TypeError: chrome.runtime.PlatformInfo is undefined
TypeError: chrome.runtime.PlatformNaclArch is undefined
TypeError: chrome.runtime.PlatformOs is undefined
TypeError: chrome.runtime.Port is undefined
TypeError: chrome.runtime.reload is undefined
TypeError: chrome.runtime.requestUpdateCheck is undefined
TypeError: chrome.runtime.RequestUpdateCheckStatus is undefined
TypeError: chrome.runtime.sendNativeMessage is undefined
TypeError: chrome.runtime.setUninstallURL is undefined
TypeError: chrome.sessions is undefined
TypeError: chrome.sidebarAction is undefined
TypeError: chrome.tabs is undefined
TypeError: chrome.thing is undefined
TypeError: chrome.topSites is undefined
TypeError: chrome.webNavigation is undefined
TypeError: chrome.webRequest is undefined
TypeError: chrome.windows is undefined
like image 140
Makyen Avatar answered Oct 22 '22 08:10

Makyen


This question led me here. I had a problem with a browserAction. This line was in my background.js for handling a click on my extensions' icon:

browser.browserAction.onClicked.addListener(handleClick);

That line gave me this error:

TypeError: browser.browserAction is undefined

What was the problem? I just forgot to define a browser_action in my manifest.json:

"browser_action": {
    "default_icon": "my-icon.png"
}

Maybe this hint could be helpful for someone else… ;-)

like image 45
Jan Köhler Avatar answered Oct 22 '22 09:10

Jan Köhler