简体   繁体   中英

How to listen to “meta” property change on the page using jquery?

I am writing a chrome extension where I want to listen to the DOM change on the page. Initially when the page loads the "head" has

<meta property="og:title" content="XYZ">

but after clicking on another link, the page does an ajax and changes the DOM.

<meta property="og:title" content="ABC">

I have this code to listen to changes in the head. But it doesn't capture the change.

$('head').on("DOMSubtreeModified", function(e){
   title = $('meta[property=og\\:title]').attr("content");
   console.log('Title - ' + title);
});

How can I listen and capture this change?

When I do var title = $('meta[property=og\\\\:title]').attr("content");

The title is always "XYZ" and it doesn't change to "ABC"

You can use MutationObserver to listen to any change made to the <meta> element.

For example:

var ob = new MutationObserver(function(mutations){
  mutations.forEach(function(m){
    if (m.type === 'attributes' && m.attributeName === 'content') {
      // Do something
    }
});

ob.observe($('meta[property=og\\:title]')[0], {attributes: true});

See also: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

Not clear how you change the meta tag value. but as you said, when the link is clicked there will be an ajax call and then it will change the meta tag. IF so you can capture the ajax complete event and get the value of the meta tag.

$( document ).ajaxComplete(function() {
   title = $('meta[property=og\\:title]').attr("content");
   console.log('Title - ' + title);
});

In your Chrome Extension you can use following code

var scriptContent = '(' + function() {
    $(document).ajaxComplete(function() { 
      var title = $('meta[property=og\\:title]').attr("content");
      console.log('Title - ' + title);    
    });
} + ')();';
var script = document.createElement('script');
script.textContent = scriptContent;
(document.head||document.documentElement).appendChild(script);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM