Tharaka Deshan
Tharaka Deshan

Reputation: 1396

How to access a page element from a background js of chrome extension

I have a context menu in my chrome extension and now I need to capture a specific page elements when the user click on that menu. This is my manifest file:

{
  "manifest_version": 2,
  "name": "Capture",
  "description": "This extension is capturing all text elements in the page",
  "version": "0.1",
  "permissions": ["contextMenus"],
  "background": {
    "scripts": ["jquery-2.0.2.js", "background.js"]
  },
  "manifest_version": 2
}

background.js

function captureTextBoxes(e) {
    var textboxes = $(':text') ; 
        //alert(textboxes.length);
        textboxes.each(function (i){
        //code here
    }
}

chrome.contextMenus.create({
    title: "Capture All text box Elements", 
    contexts:["page"], 
    onclick: captureTextBoxes,
});

This was capturing 0 text box elements always. So I checked the passed document by adding following line:

    alert(document.documentElement.innerHTML);

It returns this :

    <head></head>
    <body style="">
        <script src="jquery-2.0.2.js"></script>
        <script src="background.js"></script>
    </body>

This is not my actual page, but a dynamic page created by the chrome itself. Is there anyway to access the actual page content that were right clicked for the context menu? (From a background javaScript)

Upvotes: 3

Views: 3465

Answers (1)

gkalpak
gkalpak

Reputation: 48211

The contextMenus.onClicked event (which triggers the callback specified by onclick (in persistent background pages only)) is only available to the background page and the background page has no direct access to any web-page's DOM.

If you want to manipulate the web-page DOM, you have to:

  1. Inject a content script into the web-page.
  2. Pass a message to that content script, so it can manipulate the DOM for you.

(There are plenty of resources here in SO explaining how to achieve both.)

Take, also, a look at this answer to a similar question

Upvotes: 3

Related Questions