0

我正在尝试为 Chrome 制作一个自动登录到此网页的扩展程序。它通过检测我何时进入页面来做到这一点,然后它将浏览器重定向到登录页面,在那里它填写用户名和密码并单击登录按钮。

清单.json:

{
    "manifest_version": 2,

    "name": "Login",
    "description": "Automaticly logs in to a page",
    "version": "1.0",
    "background": {
        "scripts": ["background.js"],
        "persistent": false
    },

    "permissions": [
        "tabs",
        "http://*/"
    ]
}

背景.js:

window.onload = function() {
    chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
        if (tab.url == "https://www.itslearning.com/Index.aspx?customerid=&username=&redirectlogin=itslearning.com&MustUseSsl=true&") {
            chrome.tabs.update(tabId, {"url": "https://vaf.itslearning.com/elogin/"}, function(){});
        } else if(tab.url == "https://vaf.itslearning.com/elogin/") {
            var username = document.getElementById("ctl00_Username"); //doesn't work
            var password = document.getElementById("ctl00_Password"); //doesn't work
            var button = document.getElementById("ctl00_ButtonLogin"); //doesn't work
            if (username && password && button) {
                username.value = "####";
                password.value = "######";
                button.click();
            }
        }
    });
};

我通过右键单击-> 检查 chrome 中的元素获得了字段的 ID。当我第一次运行它时,它会将浏览器重定向到正确的页面,但它没有填写密码和用户名,所以我做了一些快速调试,似乎它永远找不到任何字段。我在论坛里搜索,发现页面必须先完全加载,所以我添加了,window.onload=function(){}但它仍然不起作用。为什么?

我以前在 javascript 中编程过一点,但我是 chrome 扩展开发的新手,所以如果有人有一些额外的提示或建议,请与我分享。

4

1 回答 1

2

后台脚本不能直接与常规页面的 DOM 交互。当您document在后台脚本中使用时,您指的是 Google Chrome 为您的扩展程序创建的后台页面的 DOM。

要访问网页的 DOM,您需要一个内容脚本。您可以在清单中指定它或使用chrome.tabs.executeScript. 在您的情况下,您希望始终在特定 URL 中运行它,最简单的方法是通过清单:

"content_scripts": [
  {
    "matches": ["https://vaf.itslearning.com/elogin/"],
    "js": ["content.js"]
  }
],

在您的 content.js 中,您可以放置​​:

var username = document.getElementById("ctl00_Username");
var password = document.getElementById("ctl00_Password");
var button = document.getElementById("ctl00_ButtonLogin");
if (username && password && button) {
   username.value = "####";
   password.value = "######";
   button.click();
}

所以在你的 background.js 中你只需要留下重定向代码:

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    if (tab.url == "https://www.itslearning.com/Index.aspx?customerid=&username=&redirectlogin=itslearning.com&MustUseSsl=true&")
        chrome.tabs.update(tabId, {"url": "https://vaf.itslearning.com/elogin/"});
}

(顺便说一句,有更有效的方法可以使用 引起重定向chrome.webRequest

于 2013-09-27T17:23:49.553 回答