0

I have a chrome extension that passes information as follows: 1. content.js analyzes the page and sends the result to background.js 2. popup.js queries the result from background.js and displays it in popup.html.

Expected behavior: each time the user clicks the popup button, he will see the analyzed data of the current tab.

Current behavior: each time the user clicks the popup button, he sees the analyzed data of the first tab that it analyzed.

I tried using chrome.tabs.query but I failed to figure it out. what is the way to go here?

Content.js (sending DOM to background)

var fromDOM = new XMLSerializer().serializeToString(document);
console.log(fromDOM);

chrome.runtime.sendMessage({method:'setTitle',title:fromDOM});

Background.js (proxies between content and popup)

var title;
chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
  if(message.method == 'setTitle')
    title = message.title;
  else if(message.method == 'getTitle')
    sendResponse(title);
});

popup.js (display DOM)

chrome.runtime.sendMessage({method:'getTitle'}, function(response){
    document.querySelector("p").textContent = response;
  });  

manifest

{
    "manifest_version": 2,
    "name": "B",
    "version": "0.1",
    "options_page": "options.html",
    "background" : {
        "scripts": ["background.js"]
    },
    "permissions": [
        "storage",
        "tabs"
    ],

    "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "popup.html"
    },

    "content_scripts": [
        {
            "matches": [
                "<all_urls>"
            ],
            "js": ["content.js"],
            "run_at": "document_end"
        }
    ]

}
toti
  • 139
  • 1
  • 2
  • 9
  • Can you add your manifest (and code that injects the content script, if it's not from the manifest)? Also, tell me when do you expect `content.js` to be run. – Xan Mar 24 '19 at 16:49
  • Generally, I think this answer of mine would be a very helpful read: https://stackoverflow.com/q/31111721/934239 – Xan Mar 24 '19 at 16:50
  • Hey, thanks for trying to help! updated the original post with manifest. I expect content.js to run every new tab load, but I don't want the user to have to trigger something. reading your post now – toti Mar 24 '19 at 17:24
  • @Xan your the bomb! your advise totally worked. why can't i upvote you? :) – toti Mar 24 '19 at 18:03
  • You need a minimum of 10 reputation to do that. Let me close this as a duplicate if you think that answer was enough to help – Xan Mar 25 '19 at 10:10

0 Answers0