Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

javascript - How to listen for url change with Chrome Extension

I am writing a Google Chrome extension to automate some common tasks. The functionality I want is as follows:

  1. Create a new tab and navigate to my webmail
  2. enter username and password
  3. click "submit" button
  4. Wait until the webmail page appears, and choose the "roundcube" client.

I have completed steps 1,2,and 3 and they work. I am having a lot of trouble trying to listen for the url change after my credentials are submitted so that the function that selects roundcube client can run

I know I can run a script when client selection page appears by adding to my manifest but I want to use "chrome.tabs.executeScript" instead so that roundcube is chosen only if I run the script from the chrome extension and not if I go to client selection page manually.

Here is my 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://*/*"
  ]
}

Here is my chrome script:

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();
    });

});

and here is the content script to be executed as a callback of tab creation (when the email login page is fetched and the DOM has loaded), and also when the email credentials are submitted and the client selection page's DOM has loaded (which is not working right now)

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');
    }
}()

any help would be appreciated... thanks!

question from:https://stackoverflow.com/questions/34957319/how-to-listen-for-url-change-with-chrome-extension

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As mentioned by NycCompSci you cannot call the chrome api from content scripts. I was able to pass api data to content scripts with message passing though, so thought I'd share that here. First call onUpdated in background.js:

Manifest

{
  "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

    }
  }
);

Then you can expand that script to send data (including the new url and other chrome.tabs.onUpdated info) from background.js to your content script like this:

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
      })
    }
  }
);

Now you just need to listen for that data in your content script:

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!
    }
});

Hope that helps someone! ???


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...