Chrome扩展程序:获取当前标签页的源代码

4
当点击Chrome扩展程序图标时,我需要获取当前选项卡的源代码。我也尝试过使用按钮单击事件。请查看我的当前代码:
manifest.json
    {  "name": "UM Chrome Extension!",  "version": "1.0",
  "description": "To ensure the tracking codes present.",
    "icons": {
"128": "TW-Extension-Icon2.png"
},   "background": {
      "scripts": [ "background.js"]
   }, 
  "content_scripts": [
    {
      "matches": ["http://*/*"],  
      "js": ["popup1.js","jquery-1.10.2.js","jquery-ui.js","bootstrap.min.js"]
    }
    ], 
    "permissions": [
    "activeTab","tabs","contextMenus", "http://*/*"
  ],

  "browser_action": {
    "default_popup": "popup.html"
  },
  "manifest_version": 2
}

popup.html

<!doctype html>
<html class="no-js" lang="">
    <head>
        <script type="text/javascript" src="popup1.js"></script>
    </head>

    <body style="width: 600px; height: 300px;">
<button value="Test" id="check-1"> </button>
</body>
</html>

和 popup.js

window.addEventListener('DOMContentLoaded', function() {
var fbshare = document.querySelector('#check-1');
    fbshare.addEventListener('click', function() {
        var htmlCode = document.documentElement.outerHTML;
     window.alert(htmlCode);
      });

});

如何获取当前活动标签页的源代码? 我需要获取页面的源代码,以便搜索页面是否包含特定的跟踪代码(例如GA代码)。
谢谢你。

请定义“源代码”。您是指HTML吗?脚本?CSS? - Makyen
你正在为弹出窗口和内容脚本都加载 popup1.js。这几乎总是一个糟糕的想法™。你只应该将其作为其中一个加载。除了库之外,任何脚本文件在两者之间共享都非常罕见。 - Makyen
请不要在每个页面中加载jQuery、jQueryUI和BootStrap(使用您的匹配项的content_scripts),除非您确实需要。仅jQuery本身就有85kiB的最小化代码。这对于每个页面来说是一个重大负担。那些打开了数百个选项卡的人怎么办?虽然可能确实需要加载所有这些库,但您应该加载绝对最少量的内容,以允许用户开始与您的扩展程序进行交互(例如,一个静态图像和事件处理程序,没有库),然后在用户实际与您的扩展程序进行交互时动态加载所有内容。 - Makyen
不太清楚你真正想要什么。你需要哪些代码?你想把它放在哪里?你已经定义了一个内容脚本,所以你可以直接在那里获取它。对于你所问的一些解释,你应该能够进行一些搜索并得到答案。 - Makyen
可能是重复的问题:从 Chrome 扩展程序中获取当前页面的源 HTML - Paul Roub
1个回答

13
您的清单文件同时包含 "content_scripts" (在页面上下文中使用document_idle运行)和 "browser_action" 脚本(在单击扩展菜单按钮时在隔离的上下文中运行)。
popup.html 中,您引用了 popup.js,因此在 popup.js 中调用 document.documentElement.outerHTML 时会获取到 popup.html 的内容,而不是当前活动标签页的内容。
您同时引用了 popup.jspopup1.js,这很令人困惑。您目前在弹出窗和页面上下文中运行相同的代码,几乎肯定会在其中一个地方出现问题。按照惯例,在 "content_scripts" 中使用 content.js,在操作中的 popup.html 中引用 popup.js"content_scripts"每个页面中运行,无论用户是否单击了扩展。您当前的清单文件正在向每个页面添加["popup1.js","jquery-1.10.2.js","jquery-ui.js","bootstrap.min.js"],这会导致不必要的缓慢。
避免在 Chrome 扩展中使用 jQuery。它相当庞大,而且作为浏览器标准化库在你知道所有用户都在 Chrome 上的情况下并没有太多用处。如果你无法在没有它的情况下编写代码,请尝试将其限制在弹出窗口中或动态加载它。
您设置了一个 "scripts": [ "background.js"],它会在后台不停地运行,但在您目前的代码中根本不需要。如果您需要在操作按钮之外进行操作,请考虑改用事件页面
使用 Chrome API 将上下文从弹出窗口获取到页面。您需要查询chrome.tabs以获取活动选项卡,然后调用chrome.tabs.executeScript 在该选项卡的上下文中执行脚本。
Google 的 API 使用回调函数,但在这个例子中我将使用 chrome-extension-async 来允许使用 promises(还有其他库也可以做到这一点)。
popup.html 中(假设您使用 bower install chrome-extension-async):
<!doctype html>
<html>
<head>
    <script type="text/javascript" src="bower_components/chrome-extension-async/chrome-extension-async.js"></script>
    <script type="text/javascript" src="popup.js"></script>
</head>

<body style="width: 600px; height: 300px;">
    <button value="Test" id="check-1"> </button>
</body>
</html>

popup.js中(放弃popup1.js):

function scrapeThePage() {
    // Keep this function isolated - it can only call methods you set up in content scripts
    var htmlCode = document.documentElement.outerHTML;
    return htmlCode;
}

document.addEventListener('DOMContentLoaded', () => {
    // Hook up #check-1 button in popup.html
    const fbshare = document.querySelector('#check-1');
    fbshare.addEventListener('click', async () => {
        // Get the active tab
        const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
        const tab = tabs[0];

        // We have to convert the function to a string
        const scriptToExec = `(${scrapeThePage})()`;

        // Run the script in the context of the tab
        const scraped = await chrome.tabs.executeScript(tab.id, { code: scriptToExec });

        // Result will be an array of values from the execution
        // For testing this will be the same as the console output if you ran scriptToExec in the console
        alert(scraped[0]);
    });
});
如果您使用这种方式,就不需要在manifest.json中添加任何 "content_scripts"。也不需要使用jQuery、jQuery UI或Bootstrap。

谢谢Keith!你的代码非常有帮助 :) - ForTW
@ForTW 你好。如果这个回答解决了你的问题,请点击左侧的绿色勾选框将其选为答案。如果还有其他需要,请告诉我。 - Keith
这个答案让我离解决方案更近了,比以往任何时候都要近。但是,它并没有获取到源<head>。返回的HTML头只包含popup.html文件的头。难道真的没有办法获取整个页面的HTML源码吗? - Lasserh
@Lasserh,这听起来像是你在内联调用 - 你需要调用chrome.tabs.executeScript来确保脚本从你想要的标签页获取HTML。 - Keith

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接