【问题标题】:Chrome extension : get source code of active tab [closed]Chrome 扩展:获取活动标签的源代码 [关闭]
【发布时间】:2017-04-20 05:35:59
【问题描述】:

单击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?
  • 您正在为弹出窗口和内容脚本加载 popup1.js。这几乎总是一个坏主意™。您应该只将它作为一个或另一个加载。除了库之外,很少有任何脚本文件在两者之间共享。
  • 不要将jQuery、jQueryUI和BootStrap加载到每个页面(content_scriptsmatches),除非你需要。仅 jQuery 就是 85kiB 的最小化代码。这对每一页来说是一个很大的负担。我们这些打开了 100 个标签的人呢?虽然您可能确实需要加载所有这些库,但您应该加载允许用户开始与您的扩展程序交互所需的绝对最小值(例如静态图像和事件处理程序 w/o 库),然后在用户实际与您的扩展交互时动态加载所有内容。
  • 不清楚您真正要问的是什么。你要什么代码?你要在哪里?你已经定义了一个内容脚本,所以你可以在那里得到它。对于您所询问的内容的至少一些解释,您应该能够进行一些搜索并获得答案。

标签: google-chrome google-chrome-extension


【解决方案1】:

您的清单包含 "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"],它在后台持续运行,并且在您当前的代码中根本不需要。如果您需要在操作按钮之外执行操作,请考虑改用 event pages

使用 Chrome API 从弹出窗口的上下文中获取页面。您需要 query chrome.tabs 来获取活动选项卡,然后调用 chrome.tabs.executeScript 在该选项卡的上下文中执行脚本。

Google 的 API 使用回调,但在本例中,我将使用 chrome-extension-async 来允许使用 Promise(还有其他库也这样做)。

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。

【讨论】:

  • 谢谢基思!你的代码很有帮助:)
  • @ForTW 欢呼。如果这回答了您的问题,请单击左侧的绿色勾号将其选为答案。如果没有,请告诉我您还需要什么。
  • 这个答案让我比以往任何时候都更接近我的解决方案。但是,这并没有得到源 。返回的 html 的头部仅包含 popup.html 文件的头部。难道真的没有办法获取整个页面的html源码吗?
  • @Lasserh 这听起来像是您将其称为内联 - 您需要调用 chrome.tabs.executeScript 以确保脚本从您想要的选项卡中获取 HTML。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-30
  • 1970-01-01
  • 1970-01-01
  • 2014-06-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多