如何倾听" meta"使用jquery在页面上更改属性?

时间:2015-08-14 06:06:30

标签: javascript jquery google-chrome-extension meta-tags meta

我正在写一个chrome扩展,我想在页面上听DOM更改。最初当页面加载" head"具有

loadonce: true

但点击另一个链接后,页面会执行ajax并更改DOM。

import UIKit func RBSquareImageTo(image: UIImage, size: CGSize) -> UIImage { return RBResizeImage(RBSquareImage(image), size) } func RBSquareImage(image: UIImage) -> UIImage { var originalWidth = image.size.width var originalHeight = image.size.height var edge: CGFloat if originalWidth > originalHeight { edge = originalHeight } else { edge = originalWidth } var posX = (originalWidth - edge) / 2.0 var posY = (originalHeight - edge) / 2.0 var cropSquare = CGRectMake(posX, posY, edge, edge) var imageRef = CGImageCreateWithImageInRect(image.CGImage, cropSquare); return UIImage(CGImage: imageRef, scale: UIScreen.mainScreen().scale, orientation: image.imageOrientation) } func RBResizeImage(image: UIImage, targetSize: CGSize) -> UIImage { let size = image.size let widthRatio = targetSize.width / image.size.width let heightRatio = targetSize.height / image.size.height // Figure out what our orientation is, and use that to form the rectangle var newSize: CGSize if(widthRatio > heightRatio) { newSize = CGSizeMake(size.width * heightRatio, size.height * heightRatio) } else { newSize = CGSizeMake(size.width * widthRatio, size.height * widthRatio) } // This is the rect that we've calculated out and this is what is actually used below let rect = CGRectMake(0, 0, newSize.width, newSize.height) // Actually do the resizing to the rect using the ImageContext stuff UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0) image.drawInRect(rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage }

我有这个代码来听取头部的变化。但它并没有捕捉到变化。

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

我如何倾听并捕捉这一变化?

当我做<meta property="og:title" content="ABC">

标题总是&#34; XYZ&#34;并且它不会改变为&#34; ABC&#34;

2 个答案:

答案 0 :(得分:3)

您可以使用MutationObserver收听对<meta>元素所做的任何更改。

例如:

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

另请参阅:https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

答案 1 :(得分:0)

不清楚如何更改元标记值。但正如你所说,当点击链接时会有一个ajax调用,然后它会改变元标记。如果您这样,您可以捕获ajax完成事件并获取元标记的值。

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

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