javascript firefox firefox-webextensions

javascript - TypeError:[API] no está definido en el script de contenido o ¿Por qué no puedo hacer esto en un script de contenido?



firefox firefox-webextensions (2)

Las secuencias de comandos de contenido no tienen acceso a la API que está utilizando

Estás intentando hacer esto desde un script de contenido . Debe hacer esto desde un script de fondo . Los scripts de contenido tienen acceso a un pequeño subconjunto de las API de WebExtensions. Las API disponibles incluyen (desde la página de secuencias de comandos de contenido de MDN ):

De la extension :

Desde runtime :

Desde i18n :

Todo desde el storage .

Esto no incluye la API que está intentando utilizar (por ejemplo, webRequest ).

Cambie su manifest.json para usar una página de background

Debe cambiar su manifest.json a en lugar de tener una clave content_scripts para su xframeoptions.js , ejecútelo como un script de background usando algo como:

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

Las extensiones se separan en scripts de fondo y scripts de contenido.

Si necesita que la información llame a la API en su secuencia de comandos de contenido, deberá utilizar el webRequest . Sin embargo, a menudo puede mover la lógica completa a un script que se ejecuta en el contexto de fondo (scripts de fondo, scripts emergentes, scripts de página de opciones, etc.). Lo que se requerirá exactamente dependerá de lo que desee lograr con su guión.

Esta separación de la funcionalidad entre todas las API privilegiadas disponibles en el contexto de fondo y el acceso al contenido de la página web disponible en scripts de contenido (con acceso muy limitado a API privilegiadas), con mensajes asíncronos entre ellas, es fundamental para la arquitectura de las extensiones . Deberá diseñar su extensión en torno a esta arquitectura.

Algunos posibles errores que pueden ser causados ​​por este problema

Hay una serie de posibles errores que pueden ser causados ​​por este problema. La siguiente es una lista incompleta de posibles errores:

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

Intenté escribir una extensión simple en Firefox en la que modifico el encabezado X-Frame-Allow .

Miré brevemente la documentación y veo que admiten webRequest.onHeadersReceived.addListener() . Sin embargo, no puedo ejecutar mi código cuando se reciben los encabezados.

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"] );

¿Cómo modifico los encabezados de respuesta a través de WebExtensions de Firefox?


Esta pregunta me llevó aquí. Tuve un problema con un browserAction. Esta línea estaba en mi background.js para manejar un clic en el icono de mis extensiones:

browser.browserAction.onClicked.addListener(handleClick);

Esa línea me dio este error:

TypeError: browser.browserAction no está definido

¿Cual fue el problema? Olvidé definir una browser_action en mi manifest.json:

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

Tal vez esta pista podría ser útil para otra persona ... ;-)