使用chrome扩展进行查询并获取源代码

Make queries and get source code with chrome extension

本文关键字:获取 源代码 查询 chrome 扩展 使用      更新时间:2023-09-26

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

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

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

我想这样做:在后台页面中,每隔一段时间,使用Cookie会话加载一个页面(用于浏览带有登录系统的网站)。然后获取加载页面的源代码,然后做一些事情(比如对用户说,如果他有消息,但我认为这不是主题,也不是问题)。

所以我至少需要:

  • 使用Cookie和会话进行查询
  • 访问web托管页的源代码
  • 在后台页中执行所有这些操作(隐藏并分离用户的浏览)

我可以用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();

是的,您可以通过一个简单的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。

谷歌在扩展中有一个跨域请求页面。您可以在此处阅读更多信息:https://developer.chrome.com/extensions/xhr#requesting-许可

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