Kevin Ku
Kevin Ku

Reputation: 53

How to get document from current tab in background.js

I'm making a chrome extension that shows notifications, when the user clicks the button on the notification it opens an html file in a new tab through background.js that I need to modify after an api call, but I can't find a way to access that page through my background.js.

manifest.json Permissions "permissions": ["http://*/*", "https://*/*","notifications", "webNavigation", "storage", "tabs","activeTab", "background" ]

part of background.js

chrome.notifications.onButtonClicked.addListener(function() {
  chrome.tabs.create({'url': 'index.html'}, (tab) => {
    chrome.tabs.executeScript(tab,add_new_card());
  });
});


function add_new_card(){
  var elm= document.getElementById("cards");
  console.log(document);
  let new_card = '<div class="col-5 col-md-3 col-lg-2 p-0 mr-2 col"> ' +
                     '<div class="card"> ' +
                        '<a class="text-center" href=""> ' +
                        '<div class=" f-16 text-dark mt-4 card-title"> '+
                        '<strong class="text-capitalize">NEW CARD</strong> '+
                      '</div> </a>  </div> </div> ';
  elm.append(new_card);
}

I've tried a lot of things but I always get null from document.getElementById("cards").

Upvotes: 2

Views: 2177

Answers (1)

fohletex
fohletex

Reputation: 96

I haven't worked with the "executeScript" command yet, since I always used common content-scripts for that, but as far as I see in the official documentation, you need to insert your code within a JS-object { code: '<your_actual_code>' }, whereas <your_actual_code> is put into a string.

E.g.

chrome.tabs.executeScript({ code: "console.log('Hello World!')" }, callback);

If you don't want to put your code in a complete string, which I could understand and wouldn't recommend, you could also exclude your method (without the function wrapper!) into an additional file. In this case you can execute the code via

chrome.tabs.executeScript({ file: "/my-code.js" }, callback);

Note callback needs to be defined again in your background.js and appended without the brackets; otherwise you execute the callback immediately, before the executeScript command has been performed! If you don't need a callback, you can exclude it from the above code examples.

Upvotes: 4

Related Questions