How can I retrieve og/meta attributes of a resource?

前端 未结 3 1334
死守一世寂寞
死守一世寂寞 2021-01-04 22:28

I\'m making an application that retrieve tweets on Twitter of a user.

Those feeds contains links to external resources, such as Artciles, Webpage or YouTube video.

3条回答
  •  暖寄归人
    2021-01-04 23:01

    Anyone finding this question who is looking for a way to grab OG (open graph) metadata values using the browser console (Chrome or other) can do it using ES6 JavaScript.

    Example:

    To grab the "description" tag, (which will also return the site byline for WordPress website) use this one-liner code snippet I wrote to do just that:

    document.querySelectorAll('meta[property="og:description"]')[0]

    This does not address grabbing stuff remotely off a server with Ajax, this is simply a browser-based solution.

    Here is another quick example. Let's say you want to grab all the metadata properties and store them in an object that can be passed. This is most easily tested on a good WordPress website, but should work wherever there are open graph meta tags.

    /*
    
    10/01/18
    
    Eric Hepperle
    
    Grab all OG Meta Tags values on a webpage
    
    Total time spent to create and test: 1 hr.
    
    */
    
    console.clear();
    
    // Store all our properties in one object
    var ogWebsite = {};
    
    //var metas = document.querySelectorAll('meta[property="og:description"]')[0]
    var metaTags = document.querySelectorAll('meta');
    
    var propTagCount = 0;
    
    [...metaTags].forEach(function(tag, i) {
        
        // console.log(tag);
        
        if (tag.hasAttribute('property')) {
            
            var propName = tag.getAttribute('property');
            // console.log("%c\t%s", "background: orange; color: black", propName);
            console.log(propName);
    
            // Get the value of the OG property attribute
            var ogMetaValue = document.querySelectorAll("meta[property='" + propName +"']")[0].content;
            
            console.log("%cogMetaValue: %s","background: purple; color: white;", ogMetaValue);
            
            // Add property to ogWebsite object. We can do this because
            //  ES6 (2015) allows varible keys with object literals.
            //  To work, you must use bracket "[]" notation instead of dots.
            ogWebsite[propName] = ogMetaValue;
            
            ++propTagCount;        
        }
        
        
    });
    
    console.log("%cTotal meta tags: %s", "background: bisque; color: brown; font-weight: bold;", metaTags.length);
    console.log("%cTotal meta tags with 'property' attribute: %s", "background: cadetblue; color: white; font-weight: bold;", propTagCount);
    
    // Display the final object:
    console.log(ogWebsite);

    Disclaimer:

    This is an answer to the question title "How can I retrieve og/meta attributes of a resource?"

提交回复
热议问题