【问题标题】:Setting Background Image with BrowserAction使用 BrowserAction 设置背景图像
【发布时间】:2012-05-11 17:38:18
【问题描述】:

我正在学习如何编写 chrome 扩展程序,我发现了一个示例,其中使用浏览操作可以更改网页的背景颜色,我正在尝试做一些非常相似的事情,更改背景图像,但出于某种原因...它不起作用,js函数是:

function click(e) {
  chrome.tabs.executeScript(null,
      {code:"document.body.style.background=url('ffrontier.jpg')"});
  window.close();
}

我很确定这与我的 sintax 有关,但我无法弄清楚,有人可以帮助我吗?非常感谢

【问题讨论】:

    标签: javascript google-chrome background google-chrome-extension browser-action


    【解决方案1】:

    首先你需要在 manifest.json 文件中指定资源(参见Web Accessible Resources),如下所示:

    "web_accessible_resources": ["ffrontier.jpg"]
    

    其次,您应该像这样指定完整的图片网址:

    function click(e) {
      chrome.tabs.executeScript(null,
          {code:"var imgURL = chrome.extension.getURL('ffrontier.jpg'); document.body.style.backgroundImage='url(' + imgURL + ')'"});
      window.close();
    }
    

    【讨论】:

      【解决方案2】:

      更新:只有像 url(http://www.stackoverflow.com) 这样的外部 url 有效,本地文件无效。对不起。 我只是删除了url() 中的引号,它对我有用!

      function click(e) {
        chrome.tabs.executeScript(null,
            {code:"document.body.style.backgroundImage = 'url(ffrontier.jpg)'"});
      }
      

      【讨论】:

        【解决方案3】:

        您需要更改background-image 属性,而不是background 属性(指的是页面的背景颜色)。

        function click(e) {
          chrome.tabs.executeScript(null,
              {code:"document.body.style[background-image]=\"url('ffrontier.jpg')\""});
          window.close();
        }
        

        注意事项:document.body.style.background-image 会抛出错误,因为您不能在变量名中使用 - 符号。您必须改用对象语法:

        document.body.style[background-image]
        

        【讨论】:

        • 确保图片 url 也是有效的。
        • 已经检查过了,这就是图片的名称.....这不是关于“”的东西吗?
        • @xiidarkevil:我想可能是这样。稍等...--edit-- 好的,我已经更新了答案,我认为我们缺少一组引号。再试一次?
        • 应该是document.body.style.backgroundImage
        猜你喜欢
        • 1970-01-01
        • 2011-02-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多