Get DOM content with Chrome extension

Viewed 5009

Hi I'm doing a exercise in which I have to capture the content of a "p" tag inside on any page and show by "alert"

manifest.json

{
  "manifest_version": 2,
  "name": "Get text",
  "description": "Get text",
  "version": "1.0",

  "browser_action": {
     "default_title": "Get text"
  },

  "background": {
    "page": "background.html"
  },

  "permissions": [
    "tabs",
    "activeTab"
  ]
  
}

background.html

<div>BLA BLA BLA</div>
<p> p tag </p>
<script src="jquery-3.3.1.js"></script>
<script src="background.js"></script>

here I check that I was capturing the elements of this html page instead of the page opened in the tab

background.js

chrome.browserAction.onClicked.addListener(function() {
    alert("Text: " + $("p").text());
});

I'd tried to do in the easiest way, I'd been reading numerous post with a lot of diferents methods but none of them works

1 Answers

Try this in your background.js:

chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.executeScript(null, {
        code: "alert(document.querySelector('p').innerText)"
    });
});

You need to run the script in context of the current tab. To do that you have to use chrome.tabs.executeScript. You can also specify a file to run instead of code. Checkout the documentation.

Related