chrome.extension.getBackgroundPage在iframe的扩展页面中未定义

pd1*_*176 4 javascript google-chrome google-chrome-extension

我正在尝试使用chrome.extension.getBackgroundPage函数访问我的扩展程序的后台页面.

但是,我收到以下错误:

未捕获的TypeError:chrome.extension.getBackgroundPage不是函数

我打电话从我的函数bar.js文件,该文件被定义为web_accessible_resource在我manifest.json

我如何使其工作?

的manifest.json

{
  "manifest_version": 2,
  "name": "XPath Helper",
  "version": "1.0.13",
  "description": "Extract, edit, and evaluate XPath queries with ease.",
  "background": {
    "page": "background.html"
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "css": ["content.css"],
      "js": ["content.js"]
    }
  ],
  "permissions": ["http://*/", "tabs", "identity", "identity.email"],
  "icons": {
    "32": "static/icon32.png",
    "48": "static/icon48.png",
    "128": "static/icon128.png"
  },
  "web_accessible_resources": [
    "bar.css",
    "bar.html",
    "bar.js"
  ]
}
Run Code Online (Sandbox Code Playgroud)

bar.js是一个内部脚本bar.html(不是内容脚本):

// ...

document.addEventListener('DOMContentLoaded',function(){
  // previosuly chrome.extension.getBackgroundPage()
  chrome.runtime.getBackgroundPage(function(page){
    alert("hello");
  })  
})
Run Code Online (Sandbox Code Playgroud)

content.js

// ...

  this.barFrame_ = document.createElement('iframe');
  this.barFrame_.src = chrome.extension.getURL('bar.html');

  document.body.appendChild(this.barFrame_);

// ...
Run Code Online (Sandbox Code Playgroud)

Rob*_*b W 6

大多数扩展API 只能在页面在扩展过程中运行时使用,即顶级框架是非沙盒 chrome-extension:页面.

chrome-extension:非扩展进程中的帧只能访问内容脚本和网页可用的扩展API .与内容脚本不同,它们也可以在扩展名的原点使用Web平台API.例如,如果localStorage在内容脚本中使用,则访问运行内容脚本的页面的DOM存储.如果您localStoragechrome-extension:页面中使用,那么您将获得扩展程序的存储空间.

如果要访问框架中背景页面的功能,请使用扩展消息传递API在框架和背景页面之间进行通信.