如何使用Chrome扩展程序监听网址更改

时间:2016-01-22 22:56:11

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

我正在撰写Google Chrome扩展程序,以自动完成一些常见任务。我想要的功能如下:

  1. 创建新标签并导航至我的网络邮件
  2. 输入用户名和密码
  3. 点击"提交"按钮
  4. 等到Webmail页面出现,然后选择" roundcube"客户端。
  5. 我已完成步骤1,2和3并且它们可以正常工作。在提交凭据后尝试侦听网址更改时遇到很多麻烦,以便选择圆形客户端的功能可以运行

    我知道我可以在客户选择页面出现时通过添加到我的清单来运行脚本,但我想使用" chrome.tabs.executeScript"相反,只有当我从chrome扩展程序运行脚本时才选择roundcube,而不是手动转到客户端选择页面。

    这是我的manifest.json:

    {
      "manifest_version": 2,
    
      "name"       : "Chrome Autobot",
      "description": "This extension will run various automation scripts for google chrome",
      "version"    : "1.0",
    
      "browser_action" : {
        "default_icon" : "icon.png",
        "default_popup": "index.html"
      },
      "permissions": [
        "activeTab",
        "webNavigation",
        "tabs",
        "http://*/*",
        "https://*/*"
      ]
    }
    

    这是我的chrome脚本:

    jQuery(function($) {
        "Use Strict";
    
        var openWebmail = function() {
            chrome.tabs.create({
                url: 'http://mywebmaillogin.com:2095/'
            }, function() {
                chrome.tabs.executeScript(null, {file: "scripts/openEmail.js"});
            });
            chrome.tabs.onUpdated.addListener(function(){
                chrome.tabs.executeScript(null, {file: "scripts/openEmail.js"});
                alert('i work');
            });
        };
    
        var init = $('.script-init');
        init.on('click', function() {
            openWebmail();
        });
    
    });
    

    这里是作为标签创建回调执行的内容脚本(当提取电子邮件登录页面并加载DOM时),以及提交电子邮件凭据和客户选择页面时DOM已加载(现在无法正常工作)

    var openEmail = function() {
        var loc = window.location.href;
        if(loc === 'http://mywebmaillogin.com:2095/') {
            var submit = document.getElementById('login_submit');
            user.value = 'myusername';
            pass.value = 'mypassword';
            if(user.value === 'myusername' && pass.value === 'mypassword') {
                submit.click();
            }
            else {
                openEmail();
            }
        }
        if(loc.indexOf('http://mywebmaillogin:2095/') > -1 && loc.indexOf('login=1') > -1) {
            alert('I work');
        }
    }()
    

    任何帮助将不胜感激...谢谢!

3 个答案:

答案 0 :(得分:18)

如NycCompSci所述,您无法通过内容脚本调用chrome api。我能够通过消息传递将api数据传递给内容脚本,所以我想在这里分享一下。首先在background.js中调用onUpdated

清单

{
  "name": "My test extension",
  "version": "1",
  "manifest_version": 2,
  "background": {
    "scripts":["background.js"]
  },
  "content_scripts": [
    {
      "matches": ["http://*/*", "https://*/*"],
      "js": ["contentscript.js"]
    }
  ],
  "permissions": [
    "tabs"
  ]
}

background.js

chrome.tabs.onUpdated.addListener(function
  (tabId, changeInfo, tab) {
    // read changeInfo data and do something with it (like read the url)
    if (changeInfo.url) {
      // do something here

    }
  }
);

然后,您可以展开该脚本,将background.js中的数据(包括新网址and other chrome.tabs.onUpdated info)发送到您的内容脚本,如下所示:

background.js

chrome.tabs.onUpdated.addListener(
  function(tabId, changeInfo, tab) {
    // read changeInfo data and do something with it
    // like send the new url to contentscripts.js
    if (changeInfo.url) {
      chrome.tabs.sendMessage( tabId, {
        message: 'hello!',
        url: changeInfo.url
      })
    }
  }
);

现在您只需要在内容脚本中监听这些数据:

contentscript.js

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    // listen for messages sent from background.js
    if (request.message === 'hello!') {
      console.log(request.url) // new url is now in content scripts!
    }
});

希望有人帮助! ʘ‿ʘ

答案 1 :(得分:17)

使用chrome.tabs.onUpdated

<强> Maifest.json

{
  "name": "My test extension",
  "version": "1",
  "manifest_version": 2,
  "background": {
    "scripts":["background.js"]
  },
  "content_scripts": [
    {
      "matches": ["http://*/*", "https://*/*"],
      "js": ["contentscript.js"]
    }
  ],
  "permissions": [
    "tabs"
  ]
}

<强> contentscript.js

 chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    alert('updated from contentscript');
 });

<强> background.js

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    alert('updated from background');
});

答案 2 :(得分:3)

基于/感谢@ ztrat4dkyle的回答,对我有用的是

manifest.json

{
  ...
  "background": {
    "scripts":["background.js"]
  },
  "content_scripts": [
    {
      "matches": ["http://*/*", "https://*/*"],
      "js": ["content.js"]
    }
  ],
  "permissions": [
    "tabs"
  ]
}

background.js

chrome.runtime.onInstalled.addListener(function() {
  // ...

  chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
    // changeInfo object: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/onUpdated#changeInfo
    // status is more reliable (in my case)
    // use "alert(JSON.stringify(changeInfo))" to check what's available and works in your case
    if (changeInfo.status === 'complete') {
      chrome.tabs.sendMessage(tabId, {
        message: 'TabUpdated'
      });
    }
  })
});

content.js

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  if (request.message === 'TabUpdated') {
    console.log(document.location.href);
  }
})