如何使用 WebExtensions 更改背景图像?

How can I change the background image with WebExtensions?

我想用 WebExtension 更改 Firefox 新标签页 (about:newtab) 的背景图片。我试过这段代码,但它不起作用:

window.addEventListener("load",function(){
   if(window.document.URL == "about:newtab"){
       window.document.body.style.backgroundImage = "url(https://images-assets.nasa.gov/image/iss050e066094/iss050e066094~orig.jpg)"
   }
});

manifest.json:

{
  "description": "An example extension",
  "homepage_url": "",
  "manifest_version": 2,
  "name": "wallpaper",
  "permissions": [
    "alarms",
    "theme",
    "<all_urls>"
  ],
  "background": {
    "scripts": ["background.js"]
  },
  "version": "1.0",
  "gecko": {
      "strict_min_version": "55.0a2"
  }
}

提前致谢。

目前,由于安全原因,您不能更改 about: 个页面。

如果您真的想要 about:newtab 上的另一个背景图片,您将需要使用 chrome_url_overrides. Newtab overriding is available since Firefox 54 (implemented in Bug 1234150).

用您自己的实现覆盖新标签页

你会这样做:

"chrome_url_overrides" : {
  "newtab": "my-new-tab.html"
}

所以你的清单会变成这样

{
  "description": "An example extension",
  "homepage_url": "",
  "manifest_version": 2,
  "name": "wallpaper",
  "permissions": [
    "alarms",
    "theme",
    "<all_urls>"
  ],
  "background": {
    "scripts": ["background.js"]
  },
  "version": "1.0",
  "gecko": {
      "strict_min_version": "55.0a2"
  },
  "chrome_url_overrides" : {
    "newtab": "my-new-tab.html"
  }
}

实现您自己的自定义新标签页是一项非常重要的任务:

  • 您将需要实施访问次数最多的网站。您可以使用 topSites api.
  • 您可能也想实现搜索。由于您还无法阅读搜索引擎(Bug 1352598) you might want to implement search by hardcoding URLs in your addon, adding a dropdown to select your favorite search engine. Next, when the user entered a query and presses ENTER, you can replace the current "New tab" page with the search results page using the tabs.update 方法,将 url 属性 替换为搜索页面 + 查询的 url。

我打开了一个错误报告,要求 API 在 about:newtab 和 about:home 上设置背景图片。参见 Bug 1391912