How can i rerender Pinterest's Pin It button?

前端 未结 13 2142
暖寄归人
暖寄归人 2021-01-30 18:14

I\'m trying to create and manipulate the Pin It button after page load. When i change the button properties with js, it should be rerendered to get the functionality of pinning

13条回答
  •  走了就别回头了
    2021-01-30 18:41

    Here's what I did.

    First I looked at pinit.js, and determined that it replaces specially-marked anchor tags with IFRAMEs. I figured that I could write javascript logic to get the hostname used by the src attribute on the generated iframes.

    So, I inserted markup according to the normal recommendations by pinterest, but I put the anchor tag into an invisible div.

    
    
    

    Then, immediately after that, I inserted a script to slurp up the hostname for the pinterest CDN, from the injected iframe.

    //
    // pint-reverse.js
    //
    // logic to reverse-engineer pinterest buttons.
    //
    // The standard javascript module from pinterest replaces links to
    // http://pinterest.com/create/button with links to some odd-looking
    // url based at cloudfront.net. It also normalizes the URLs.
    //
    // Not sure why they went through all the trouble. It does not work for
    // a dynamic page where new links get inserted.  The pint.js code
    // assumes a static page, and is designed to run "once" at page creation
    // time.
    //
    // This module spelunks the changes made by that script and
    // attempts to replicate it for dynamically-generated buttons.
    //
    
    pinterestOptions = {};
    
    (function(obj){
    
        function spelunkPinterestIframe() {
            var iframes = document.getElementsByTagName('iframe'),
                k = [], iframe, i, L1 = iframes.length, src, split, L2;
    
            for (i=0; i0);
        }
    
        spelunkPinterestIframe();
    
    }(pinterestOptions));
    

    Then,

    function getPinMarkup(photoName, description) {
        var loc = document.location,
            pathParts = loc.pathname.split('/'),
            pageUri = loc.protocol + '//' + loc.hostname + loc.pathname,
            href = '/' + pathToImages + photoName,
            basePath = (pathParts.length == 3)?'/'+pathParts[1]:'',
            mediaUri = loc.protocol+'//'+loc.hostname+basePath+href,
            pinMarkup;
    
        description = description || null;
    
        pinMarkup = '