【问题标题】:Chrome Extension: access separate html documents from contentscriptChrome 扩展:从 contentscript 访问单独的 html 文档
【发布时间】:2013-05-18 08:03:17
【问题描述】:

我有一个加载/注入 contentscript.js 的 Chrome 扩展程序此脚本将 html 和 css 附加到网页。

目前我已将 html 和 css 写入我的 contentscript。我想要的是将 css 本身以及我的新元素的主体放在单独的文档中,主要是因为它看起来比将 html 和 css 作为 .js 文档中的文本更好。

然后在内容脚本中我会做类似的事情

node = the_html_doc.html
document.getElementsByTagName("body")[0].appendChild(node); 

但是我如何从我的内容脚本中访问这样一个单独的文档?它需要在所有选项卡中都可用(我使用 activeTab 权限),而不仅仅是清单“匹配”中的 url。

【问题讨论】:

    标签: google-chrome-extension


    【解决方案1】:

    您也许可以使用 web_accessible_resources 清单设置,然后在您的内容脚本中,您只需注入一个指向 CSS 的 chrome.extension.getURL(<filename>) 值的 link 元素,然后注入一个 script 元素键入带有 id 的 text/html,然后获取该节点的内容并将其用于您的 appendChild 调用。

    【讨论】:

      【解决方案2】:

      更好的解决方案是使用后台脚本。我所做的是创建一个名为background.html 的文件,它只存储模板。然后我设置了后台脚本 (background.js) 以与我的内容脚本 (content.js) 进行通信。内容脚本会向后台脚本发送一条带有command 的消息,表明它需要一个模板。利用 jQuery,我可以轻松地选择模板并将其返回到我的内容脚本,然后可以将其注入到页面中。

      这是代码(一点点):

      background.html

      <div id="template-1"></div>
      <div id="template-2"></div>
      ...
      

      background.js

      chrome.runtime.onMessage.addListener(function(cmd, sender, sendResponse){
          c = JSON.parse(cmd);
          if(c.cmd == "GET_TEMPLATE"){
             //respond with the template referenced by c.selector
             sendResponse($(c.selector).outerHTML);
          }
      });
      

      content.js

      var command = {cmd:"GET_TEMPLATE", selector:"#template-1"};
      chrome.runtime.sendMessage(JSON.stringify(command), function(response) {
          //and here you should get your template
          console.log(response);
          //you can start using jQuery like $(response) to alter it
      });
      

      这种方法对我来说完美无缺。我不仅在这里使用命令,而且现在在任何地方都使用它们,它与消息传递配合得很好。

      【讨论】:

        猜你喜欢
        • 2013-11-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-08
        • 2012-10-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多