0

I'm developing a new Chrome extension, that return meta of a website. My problem is that I have always the same result, even if the content of web page change. To get the correct and actual meta elements I must to refresh the tab (F5).

The code of my button is :

chrome.tabs.executeScript({file: 'app/js/get_metas.js'});

And the code of my get_metas.js is :

document.head.addEventListener("DOMContentLoaded", getMeta(), true);

function getMeta() {

const meta = document.head.querySelector("meta[property='****']").getAttribute("content");

alert(meta);
}

The result is always the same, I must refresh the page with F5 to get the actual meta element.

hansly
  • 1
  • 3
  • 1
    It can mean the site itself doesn't update its meta element on intra-site navigation, but instead uses HTML5 History API just like youtube does ([more info](https://stackoverflow.com/a/34100952)). – wOxxOm Jul 07 '19 at 16:40

1 Answers1

0

If you enter following code in your console you will see the alert immediately:

document.head.addEventListener("DOMContentLoaded", getMeta(), true);

function getMeta() {
    alert("test");
}

Reason is that the function will be called immediately. To change that remove the (), and also I believe the event is fired on the document itself (I'm not sure the event traverses down the whole document and the useCapture=true would work). So use something like:

document.addEventListener("DOMContentLoaded", getMeta, true);

It will still only fire once when document is loaded. If you need to run the function after some other event you'd need to add a listener for that event.

If you want to call your function after a change to the document (including ajax navigation) you could look into using Mutation Observers.

yezzz
  • 2,990
  • 1
  • 10
  • 19