1
votes

Let's have an imaginary extension which takes everything after '/' from url, which is done in content script. Also updates badge and change text in popup.html, which different for every tab (different tab, diff. url)

contentscript.js:

var str = document.URL;
var n = str.lastIndexOf('/');
var result = str.substring(n + 1);
chrome.runtime.sendMessage({message: "result", url: result});

eventpage.js:

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.message == "result") {
        chrome.browserAction.setBadgeText({tabId:sender.tab.id, "text" : "1"});      
      links = request.url;
        }

popup.js:

$(function () {
    var bg = chrome.extension.getBackgroundPage();
    $('#total').text(bg.links);
});

popup.html

<!DOCTYPE html>
<html>
    <head>
        <title>Plugin</title>
        <script type="text/javascript" src="jquery-1.11.3.js"></script>
        <script type="text/javascript" src="popup.js"></script>
    </head>
    <body>
        <div id='total'>Nothing</div>
    </body>
</html>

This works only on new loaded tabs, not when I click between them. For example, when I load first page "webpage.com/first" my popup's got 'first'. When I load second page(on different tab) "webpage.com/second" popup is 'second'. After that I click on the first page (on the first tab) and my popup is 'second' which I meant to be 'first'.

//badge in my project is counter, I wrote it here only for getting an idea

1
1. {message: "result"} should be {message: "result", url: result} 2. You have only one global links variable in the background page so of course it only stores the last set value. 3. The content scripts are only executed once when the tab is loaded, not on every tab switch - wOxxOm
to 3. I know it's executed once, but I'm finding a way how make popup.html to be different on every tab - Jakub Fedor

1 Answers

1
votes

If you only need to get the tab url you can do it without content scripts just by using chrome.tabs.query in popup.js:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    $('#total').text(tabs[0].url.replace(/^.+?\/([^\/]*)$/, '$1'));
});

Otherwise use chrome.tabs.executeScript in popup.js:

chrome.tabs.executeScript({
    code: "document.querySelector('p.something').textContent"
}, function(results) {
    $('#something').text(results[0]);
});

Both methods require "activeTab" permission in manifest.json.