简体   繁体   English

如何使用jQuery在页面上收听“元”属性更改?

[英]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. 我正在编写一个Chrome扩展程序,我想在此听页面上的DOM更改。 Initially when the page loads the "head" has 最初,当页面加载时,“ head”

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

but after clicking on another link, the page does an ajax and changes the DOM. 但是点击另一个链接后,页面会执行ajax并更改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"); 当我做var title = $('meta[property=og\\\\:title]').attr("content");

The title is always "XYZ" and it doesn't change to "ABC" 标题始终为“ XYZ”,并且不会更改为“ ABC”

You can use MutationObserver to listen to any change made to the <meta> element. 您可以使用MutationObserver来监听对<meta>元素所做的任何更改。

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 另请参阅: 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. 但是正如您所说,当单击链接时,将进行ajax调用,然后它将更改meta标签。 IF so you can capture the ajax complete event and get the value of the meta tag. 如果是IF,则可以捕获ajax complete事件并获取meta标签的值。

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

In your Chrome Extension you can use following code 在您的Chrome扩展程序中,您可以使用以下代码

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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