0

I am trying to create a Chrome extension to parse some data in the DOM of the current web page. I've found some examples on stack overflow but none of them work. All the examples are a few years old so I am wondering if a fundamental change has been made to Chrome extensions recently that renders a lot of these examples obsolete. In this particular example I get an alert with domContent = undefined and can't find the console.log appearing anywhere in my console. Original question is here: Chrome Extension - Get DOM content

But I'll paste the code for easy reading here:

background.js

// Regex-pattern to check URLs against. 
// It matches URLs like: http[s]://[...]stackoverflow.com[...]
var urlRegex = /^https?:\/\/(?:[^./?#]+\.)?stackoverflow\.com/;

// A function to use as callback
function doStuffWithDom(domContent) {
    console.log('I received the following DOM content:\n' + domContent);
}

// When the browser-action button is clicked...
chrome.browserAction.onClicked.addListener(function (tab) {
    // ...check the URL of the active tab against our pattern and...
    if (urlRegex.test(tab.url)) {
        // ...if it matches, send a message specifying a callback too
        chrome.tabs.sendMessage(tab.id, {text: 'report_back'}, doStuffWithDom);
    }
});

content.js

// Listen for messages
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
    // If the received message has the expected format...
    if (msg.text === 'report_back') {
        // Call the specified callback, passing
        // the web-page's DOM content as argument
        sendResponse(document.all[0].outerHTML);
    }
});

manifest.json

{
  "manifest_version": 2,
  "name": "Test Extension",
  "version": "0.0",

  "background": {
    "persistent": false,
    "scripts": ["background.js"]
  },
  "content_scripts": [{
    "matches": ["*://*.stackoverflow.com/*"],
    "js": ["content.js"]
  }],
  "browser_action": {
    "default_title": "Test Extension"
  },

  "permissions": ["activeTab"]
}
Thread7
  • 1,081
  • 2
  • 14
  • 28
  • The code is correct AFAICT. A common pitfall is that a declared content script is loaded by the browser only on page [re]load, which you should do manually after installing or reloading your extension. There's a better way: instead of declaring you can inject it on demand in onClicked listener using chrome.tabs.executeScript, in which case there's no need for messaging ([example](https://stackoverflow.com/a/30380827)). – wOxxOm Jul 05 '17 at 19:17
  • console logs within the private environment of the extension only show up in its own developer's tools console, (right click the extension icon and click inspect popup) – Patrick Evans Jul 05 '17 at 19:17
  • @PatrickEvans, outerHTML is a string, which is JSON-ifiable. – wOxxOm Jul 05 '17 at 19:18
  • @wOxxOm, true forgot about that – Patrick Evans Jul 05 '17 at 19:19
  • ok, thanks I'll look into these items. – Thread7 Jul 05 '17 at 21:10

0 Answers0