0

I want to get a variable from a page's html to load an url with this variable on a new tab. As I am a begginner, I followed Google's "Getting Started" tutorial in which they build an extension that works as popup and I am building around it.

The code that gets the variable works perfectly when I test it on the console, but when I click the button it says "Uncaught TypeError: Cannot read properties of null (reading 'getAttribute')". I imagine it happens because the popup has a separate html, so the javascript is not injected into the page I want.

Is there a quick fix to make the popup access the page's html? If not, how could this feature work in another way?

// Get variable

const client = document.querySelector('[data-client-id]').getAttribute("data-client-id");

// When button is clicked, open new tab and paste URL 

var button = document.getElementById("btn1");
button.addEventListener("click", function () {
    chrome.tabs.create({ url: "https://www.huggy.app/panel/contacts/" + client });
});

1 Answers1

1

To access the page's html you need a content script.

You can adapt the example found in the documentation:

function injectedFunction() {
  return document.querySelector('[data-client-id]').getAttribute('data-client-id');
}

const button = document.getElementById('btn1');
button.addEventListener('click', function() {
  chrome.tabs.query({active:true, currentWindow:true},tabs => {
  chrome.scripting.executeScript({
    target: { tabId: tabs[0].id },
    function: injectedFunction
  }, results => {
     chrome.tabs.create({url: 'https://huggy.app/panel/contacts/' + results[0].result});
  });
});
Iván Nokonoko
  • 4,888
  • 2
  • 19
  • 27
  • Thanks! I saw a few posts and videos regarding the scripting.executeScript, but wasn't able to understand how to apply the logic to my code. You already helped me a lot. But there's still a problem... The "results[0].result" seems to be returning "null" as well. Why is that happening? Shouldn't it return the string obtained from the injectedFunction? – pedrosanpietro Jun 17 '22 at 17:56