【问题标题】:Make queries and get source code with chrome extension使用 chrome 扩展进行查询并获取源代码
【发布时间】:2026-02-08 18:50:02
【问题描述】:

我想为 GmailChecker 附近的 chrome 创建一个扩展程序。我看过它的源代码,但是它有点复杂。它似乎使用了一些 AJAX。

我尝试使用 jQuery,但在这种情况下它不起作用(无法访问托管在其他服务器上的网站......并且由于这是 chrome 的扩展,脚本不能从同一台服务器执行)。

顺便说一句,我不确定我想用它做什么。我还不太了解 chrome 扩展,所以我需要你的帮助。

我想这样继续: 在后台页面中,定期使用 cookie-session 加载页面(用于浏览带有登录系统的网站)。然后获取加载页面的源代码,然后做一些事情(比如如果他有消息就告诉用户,但是,这不是我认为的主题也不是问题)。

所以我至少需要:

  • 使用 cookie 和会话进行查询
  • 访问网页源代码
  • 在后台页面中执行所有这些操作(隐藏并与 用户的浏览)。

我可以用 Chrome 扩展程序来做这件事吗(如果可以,你能给我一些功能或提示吗?

谢谢!!

清单:

{
  "manifest_version": 2,
  "name": "My Extension",
  "version": "1",
  "description": "Yeah, cool ext",
  "browser_action": {
    "default_popup": "file.html"
  },
  "permissions": ["tabs",
  "background",
  "*://*.google.com/"],
  "background": {
    "page": "background.html"
  }
}

background.html:

<!DOCTYPE html>
<html>
<head>
</head>

<body>
    <script src='script.js'></script>
</body>
</html>

script.js:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
    console.log(xhr.responseText);   //that's the source code
};
xhr.open("GET", "http://www.google.com", true);
xhr.send();

【问题讨论】:

    标签: javascript jquery ajax google-chrome google-chrome-extension


    【解决方案1】:

    是的,您可以通过简单的 AJAX 调用来完成这些操作:

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(){
        xhr.readyState == 4 && console.log(xhr.responseText);//that's the source code
    };
    xhr.open("GET", "http://www.google.com", true);
    xhr.send();
    

    或者在 jQuery 中:

    $.get("http://www.google.com/", function(data){
        console.log(data);
    });
    

    由于这是一个扩展,如果您在清单中正确声明了您需要访问的网站,您可以直接向另一个网站执行请求他们没有启用跨源资源共享。您不需要在中间需要一个服务器来为您执行请求并 ajax 您的服务器以获取结果。这需要 JSONP。

    Google 在扩展程序中有一个关于跨域请求的页面。你可以在这里阅读更多:https://developer.chrome.com/extensions/xhr#requesting-permission

    通过向清单文件的权限部分添加主机或主机匹配模式(或两者),扩展程序可以请求访问其来源之外的远程服务器。

    【讨论】:

    • 好吧,感谢您的关注,但是当我尝试使用 jQuery 时,我有这个错误线程:
    • @Yojin - 确保您已添加访问google.com的权限。
    • @Ohgodwhy - 你错了。由于这是一个扩展,因此后台页面可以直接访问您在清单中声明的​​每个地址。​​
    • @Yojin - 这是 Chrome 的扩展,对吧?作为证明,这里是截图:i.stack.imgur.com/hKGuV.png
    • 谁投了反对票,请发表评论。这个答案是正确的......(显然),您必须在清单更改生效之前重新加载扩展。