0

In my Google Chrome extension page I have a content script that injects a script when a particular URL is matched.

I'm trying to get some info about the tab that it's injected into so that I can do some cleanup when the tab gets closed.

To this end, I've tried calling chrome.tabs.getCurrent() from within the injected script. However, it returns undefined, which is weird because in the API it says that getCurrent()'s return

May be undefined if called from a non-tab context (for example: a background page or popup view).

and I'm calling it from within the tab...

Where am I going wrong?

user5508297
  • 805
  • 2
  • 9
  • 24
  • `content script that injects a script` - it means a ` – wOxxOm Sep 02 '16 at 18:00
  • It has access to the `chrome.runtime` API - I'm using it within my injected script. Plus, if it didn't have access to `chrome.tabs` wouldn't I see an error? – user5508297 Sep 02 '16 at 18:01
  • Only `chrome.runtime.sendMessage` and it'll work only if the site url is whitelisted in ["externally_connectable"](https://developer.chrome.com/extensions/messaging#external-webpage). – wOxxOm Sep 02 '16 at 18:02
  • @wOxxOm OK, yeah that's true. Perhaps I'm not doing this the right way then. All I want to do is perform some cleanup when the tab with my injected script gets closed. Any suggestions? – user5508297 Sep 02 '16 at 18:04
  • 2
    An obvious method would be to use [chrome.tabs.onRemoved](https://developer.chrome.com/extensions/tabs#event-onRemoved) in the background script. – wOxxOm Sep 02 '16 at 18:05
  • @wOxxOm Yes, that was what I was thinking. However, I don't want to have to keep polling the browser using `setInterval` and `chrome.tabs.query(queryInfo.url = myUrlMatch, ...)` to find the current tabs with my injected script. Is there no way of getting the tab id from the injected script? That way I could message pass it to the background page and then use `onRemoved` for that id. – user5508297 Sep 02 '16 at 18:08

1 Answers1

2

In your actual content script ask the background page to give you the tab id.

  • content.js

    var tabId; // global but not visible to the webpage as it's in an "isolated world"
    
    chrome.runtime.sendMessage('get-tabId', function(response) {
        tabId = response;
    
        // inject a page script and pass the tabId
        document.head.appendChild(document.createElement('script')).text = '(' +
            function(tabId) {
                tabId = tabId |0; // coerce to number
                console.log('Injected code got tabId: ', tabId);
            } + ')(' + tabId + ')';
    
    });
    
  • background.js

    chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
        if (msg === 'get-tabId') {
            sendResponse(sender.tab.id);
        }
    });
    
wOxxOm
  • 65,848
  • 11
  • 132
  • 136