如何让chrome扩展在页面加载时在后台执行功能?

use*_*388 1 javascript jquery google-chrome google-chrome-extension

我正在制作镀铬扩展程序以登录到wifi系统,并且目前已将其设置为必须单击扩展程序才能登录.但我希望它只需每30分钟签名一次,使用背景js我想要它检查我保存的cookie,如果已经过了30分钟,然后登录.但是只有在你第一次安装它时它才有用.

这是我的manifest.json:

{
  "manifest_version": 2,

  "name": "BCA Auto Login",
  "description": "This extension automatically signs you into the BCA wifi",
  "version": "1.0",
  "permissions": [ "cookies", "http://*/*", "https://*/*" ],
  "content_scripts": [{
    "matches": ["http://*/*","https://*/*"],
    "js": ["jquery.js","login.js"]
  }],
  "background": {
    "scripts": ["jquery.js", "background.js"]
  },
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  }

}
Run Code Online (Sandbox Code Playgroud)

这是我的background.js:

$(document).ready(function(){
    chrome.cookies.get({ url: 'urlofCookie.com', name: 'time' },
    //the cookie is a time in minutes
    function (cookie) {
        if (cookie) {
            var current = new Date();
            if((current.getMinutes() - cookie) >= 30){
                $.ajax({
                    type : 'POST',
                    url : 'https://signinURL',
                    data : {
                        username: 'username',
                        password: 'password',
                    },
                    success : workedFunction
                });
            }
        }
        else{
            cookieNotFound();
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

gka*_*pak 6

你只在页面加载时调用函数,所以难怪它在那之后不会执行.如果您想定期执行操作,可以使用chrome.alarms API创建一个警报,每30分钟触发一次(除非您将其用于其他事情,否则甚至不需要cookie).

例如:

var wifiAlarmName = "wifiSignIn";

chrome.alarms.create(wifiAlarmName, {
    delayInMinutes: 0,
    periodInMinutes: 30
});

chrome.alarms.onAlarm.addListener(function(alarm) {
    if (alarm.name === wifiAlarmName) {
        // Sign in
        ...
    }
});
Run Code Online (Sandbox Code Playgroud)