【问题标题】:Get html from a selected tab [closed]从选定的选项卡中获取 html [关闭]
【发布时间】:2012-01-13 16:25:18
【问题描述】:

所以我想在按 OK 时获取选定选项卡的 html。但是有些东西不起作用。我错过了什么?

ma​​nifest.json

{
  "name": "extension",
  "version": "1.0",
  "description": "discription",
  "content_scripts": [
    {
      "matches": ["http://www.google.com/*"],
      "js": ["contentscript.js"]
    }
  ],
  "browser_action": {
    "default_icon": "icon.png",
    "popup": "popup.html"
  },
  "permissions": [
    "http://ajax.googleapis.com/",
    "tabs"
  ]
}

popup.html

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"> </script>
</head>
<body>
<script>

function getHTML()
{

chrome.tabs.getSelected(null, function(tab) {
    chrome.tabs.sendRequest(tab.id, {method: "getHTML"}, function(response) {
        if(respond.method="getHTML"){               
            alert(response.html);  
      }
    });
});

}
</script>
 <input type="submit" value="OK" onclick ="getHTML()" />
</body>

contentscript.js

chrome.extension.onRequest.addListener(
    function(request, sender, sendResponse) {
        if(request.method == "getHTML"){
            sendResponse({html: document.all[0].outerHTML});
        }
    }
);

【问题讨论】:

  • 很难看到问题的本质。 1)“不起作用”是什么意思?你看到了什么。 2)您是否尝试过调试您的扩展程序?你有没有想出一个更集中的故障点?
  • 甚至没有警报消息,当我点击确定时没有任何反应
  • 你试过用chrome debugger调试它吗?

标签: html google-chrome tabs google-chrome-extension


【解决方案1】:

我看到两个错误: 1) popup.html 正在检查“respond”而不是“response”。 2) popup.html 正在检查 response.method 是否为“getHTML”,但 content_script 从不设置“method”字段。

【讨论】:

  • 我强烈建议您使用chrome debugger 看看发生了什么。将来会为您节省大量时间。
  • 干得好!我希望你迅速前进。我还将删除我较旧的 cmets,以便为未来的用户留下这个问题“干净”。我建议你也这样做:)
【解决方案2】:

document.all 在 Google Chrome 中未定义!

将其替换为document.getElementsByTagName("html")[0].innerHTML:

chrome.extension.onRequest.addListener(
    function(request, sender, sendResponse) {
        if(request.method == "getHTML"){
            sendResponse({html: document.getElementsByTagName("html")[0].innerHTML});
        }
    }
);

【讨论】:

  • 我不确定这是否正确 - 在 chrome 调试器上尝试 document.all 和 document.all[0] 似乎效果很好。即便如此,他也可以改用document.documentElement
猜你喜欢
  • 1970-01-01
  • 2017-12-31
  • 1970-01-01
  • 1970-01-01
  • 2022-01-19
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
相关资源
最近更新 更多