Warm tip: This article is reproduced from serverfault.com, please click

How to get HTML element in javascript in Chrome Extension

发布于 2020-11-29 15:01:29

UPDATED

I want to get value of specific html element of current tab (url )in chrome extension using Javascript. like

document.getElementById("productTitle").value;

here is my javascript code

background.js

function sendCurrentTitle(title) {
  var req = new XMLHttpRequest();
  req.addEventListener('readystatechange', function (evt) {
    if (req.readyState === 4) {
      if (req.status === 200) {
        alert('Saved !');
      } else {
        alert("ERROR: status " + req.status);
      }
    }
  });
  req.open('POST', 'http://url/a.php', true);
  req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  req.send('url=' + title);
}

chrome.browserAction.onClicked.addListener(function (tab) {
  
chrome.tabs.query({active: true}, function(tabs) {
      sendCurrentTitle(document.getElementById("productTitle").value);
});


});

manifest.json

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

  "background": {
    "persistent": false,
    "scripts": ["background.js"]
  },

"browser_action": {},

  "permissions": [
    "activeTab",
    "tabs", 
    "<all_urls>"
  ]
}

I want to get product title from this page and send it to php api. I am getting this error

Error handling response: TypeError: Cannot read property 'value' of null

Questioner
zileia
Viewed
0
Nadia Chibrikova 2020-11-30 02:02:48

Your extension scripts runs in a separate window, so it cannot access DOM of other pages via its own document object. You need to specify tabs permissions in your extension manifest, and inject asome javascript into the page itself

chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.executeScript(tab.id,{code:   `document.getElementById("productTitle").innerText`},sendCurrentTitle);
});

Please not that you need to use title[0] inside sendCurrentTitle, as the callback receives an array