Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome Extension: create a new tab, wait for it to complete loading, execute a script

I have been able to load a new tab but script executes before page load.

manifest.json :

{
  "manifest_version": 2,
  "name": "cpClips",
  "version": "1.0",
  "description": "cpClips extension to download videos from streaming sites.",
  "browser_action": {
    "default_icon": "icon.png"
  },
  "background": {
    "scripts": ["bg.js"],
    "persistent": false
  },
  "permissions": [
    "tabs"
  ]
}

bg.js :

chrome.browserAction.onClicked.addListener(function(activeTab)
{
    chrome.tabs.create({ url: 'http://127.0.0.1:8000' },function(tab) {
        alert('hi');

   });

});

I tried using chrome.tabs.executeScript along with chrome.tabs.onUpdated.addListener, but then even the new tab won't open.

An example would be nice.

like image 938
Shivendra Singh Vishen Avatar asked Jul 12 '16 20:07

Shivendra Singh Vishen


1 Answers

The callback to create occurs when the tab has been created but not necessarily when the page was loaded. You need to add a listener to the onUpdated event as well, and look at the changeInfo object passed to it's callback for the status.

chrome.browserAction.onClicked.addListener(function(activeTab)
{
    chrome.tabs.create({url:'http://127.0.0.1:8000'}, function(tab) {
    });
});

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    // make sure the status is 'complete' and it's the right tab
    if (tab.url.indexOf('127.0.0.1:8000') != -1 && changeInfo.status == 'complete') {
        chrome.tabs.executeScript(null, { 
            code: "alert('hi');" 
        });
    }
});
like image 73
Gideon Pyzer Avatar answered Oct 20 '22 19:10

Gideon Pyzer