【问题标题】:Inject HTML into a page from a content script从内容脚本将 HTML 注入页面
【发布时间】:2013-04-26 09:21:23
【问题描述】:

我正在构建一个 Chrome 扩展程序,并且我需要在几个网站上覆盖一个 html 块。目前我正在使用 JQuery .Get 从我的服务器中提取 html。为了提高性能,我想知道是否可以将 html 作为文件包含在扩展目录中并直接从那里访问源代码?有谁知道这是否可能?

更新

Rob 的建议完成了这项工作(请参阅已接受的答案)。唯一的附加步骤是在 web_accessible_resources 下的清单中注册文件。

{
   ...
   "web_accessible_resources": [
       "myimportfile1.html",
       "myimportfile2.html"
    ],
    ...
}

【问题讨论】:

    标签: google-chrome google-chrome-extension


    【解决方案1】:

    是的,这是可能的。使用 chrome.runtime.getURL 获取资源的绝对 URL。例如:

    第 1 步(标准 JavaScript):

    fetch(chrome.runtime.getURL('/template.html')).then(r => r.text()).then(html => {
      document.body.insertAdjacentHTML('beforeend', html);
      // not using innerHTML as it would break js event listeners of the page
    });
    

    第 1 步(jQuery):

    $.get(chrome.runtime.getURL('/template.html'), function(data) {
        $(data).appendTo('body');
        // Or if you're using jQuery 1.8+:
        // $($.parseHTML(data)).appendTo('body');
    });
    

    第 2 步:

    web_accessible_resources下的ma​​nifest.json中注册资源:

      "web_accessible_resources": [
        "template.html",
        "foo.jpg"
      ]
    

    【讨论】:

    • 完美运行,谢谢!唯一的额外步骤是在 web_accessible_resources 下的清单中注册资源:developer.chrome.com/extensions/…
    • @Chamnap 就我而言,我的内容脚本中有这段代码。
    • @Vidit 将 JS 放入内容脚本中。如果不需要,则应避免在网页中注入脚本。
    • @ViditSaxena 与直接在页面中插入元素相比,框架或影子 DOM 与页面的隔离效果要好得多。但请阅读有关此主题的现有问题和答案,而不是在此答案中添加更多不相关的评论。如果发现您的问题在任何地方都没有涉及,那么您可以发布一个新问题,其他有相同问题的人可以更轻松地找到问答。
    • 你知道我为什么收到“$ is not defined”
    【解决方案2】:

    另一种方法是使用新的Fetch API

    如果文件名是modal.html - 相应地更新manifest.json

        "web_accessible_resources": [
            "modal.html",
        ],
    

    并像这样注入它:

        fetch(chrome.runtime.getURL('/modal.html'))
            .then(response => response.text())
            .then(data => {
                document.getElementById('inject-container').innerHTML = data;
                // other code
                // eg update injected elements,
                // add event listeners or logic to connect to other parts of the app
            }).catch(err => {
                // handle error
            });
    

    【讨论】:

    • 感谢重要的 manifest.json 提及!!!错误消息只会引发无法获取状态码 (0)
    • @wOxxOm 谢谢,更新答案以反映您的建议。
    【解决方案3】:

    这是我使用同步 XHR 的方法:

    var xmlHttp = null;
    
    xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", chrome.runtime.getURL ("src/inject/inject.html"), false );
    xmlHttp.send( null );
        
    var inject  = document.createElement("div");
    inject.innerHTML = xmlHttp.responseText
    document.body.insertBefore (inject, document.body.firstChild);
    

    没有 jQuery 等

    【讨论】:

    • 看起来 Chrome 浏览器已经在主线程上弃用了 XMLHttpRequest()。这就是我在为 browserAction.click 方法采用此代码时得到的结果:Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/.
    • .open()的最后一个参数更改为true,它将是异步的
    • 为了实现异步,我必须将.open() 的最后一个参数更改为true 并将最后三行代码包装在xmlHttp.onload = function () { ... }
    【解决方案4】:

    我使用此代码。只需 3 行代码,不需要任何 jquery 的垃圾。

    var iframe  = document.createElement ('iframe');
    iframe.src  = chrome.runtime.getURL ('iframe.html');
    document.body.appendChild (iframe);
    

    【讨论】:

    • 不错的答案,但渲染搜索的(低)成本会稍微长一点(document.getElementById("myFrame").contentWindow.document.getElementById("whatever");
    • 嗯,刚刚发现它也对CORS造成了问题:stackoverflow.com/questions/3076414/…,这并不是那么容易规避的。
    【解决方案5】:

    如果您在 Chrome 扩展程序中使用 Angular,则可以使用 ng-include

    var injectedContent = document.createElement("div");
    injectedContent.setAttribute("ng-include", "");
    //ng-include src value must be wrapped in single quotes
    injectedContent.setAttribute("src", "'" + chrome.runtime.getURL("template.html") + "'");
    existingElement.appendChild(injectedContent);
    

    【讨论】:

      猜你喜欢
      • 2016-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-01
      • 1970-01-01
      • 2011-12-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多