prosource

어떻게 하면 핀터레스트의 핀 잇 버튼을 렌더링할 수 있습니까?

probook 2023. 8. 26. 11:58
반응형

어떻게 하면 핀터레스트의 핀 잇 버튼을 렌더링할 수 있습니까?

페이지 로드 후에 핀 잇 버튼을 만들고 조작하려고 합니다.js로 버튼 속성을 변경할 때 동적으로 로드된 이미지를 고정하는 기능을 얻으려면 다시 렌더링해야 합니다.그렇다면, Pinterest는 페이스북의 B와 같은 방법을 가지고 있습니까?XFBML.parse() 함수?

감사합니다...

그냥추를 추가하세요.data-pin-build에 대한 .SCRIPT 태그:

<script defer
  src="//assets.pinterest.com/js/pinit.js"
  data-pin-build="parsePinBtns"></script>

그것이 원인이 됩니다.pinit.jsbuild 세에대기능에 window로서 반대하는.parsePinBtns기능.

그런 다음 암시적 요소의 링크나 페이지의 모든 링크를 구문 분석하는 데 사용할 수 있습니다.

// parse the whole page
window.parsePinBtns();

// parse links in #pin-it-buttons element only
window.parsePinBtns(document.getElementById('pin-it-buttons'));

힌트: 0개를 표시하려면 추가하십시오.data-pin-zero="1"SCRIPT꼬리표를 달다

가장 좋은 방법은 다음과 같습니다.

  1. 조작할 핀 잇 버튼의 iframe을 제거합니다.
  2. 원하는 대로 조작하는 새 단추에 html 추가
  3. 스크립트를 다시 로드합니다. 즉, jQuery를 사용합니다.

    $.ajax({ url: 'http://assets.pinterest.com/js/pinit.js', dataType: 'script', cache:true});
    

페이지가 로드된 후 핀 잇 버튼을 렌더링하려면 다음을 사용할 수 있습니다.

<a href="..pin it link.." id="mybutton" class="pin-it-button" count-layout="none">
    <img border="0" src="//assets.pinterest.com/images/PinExt.png" width="43" height="21" title="Pin It" />
</a>
<script>
    var element = document.getElementById('mybutton');
    (function(x){ for (var n in x) if (n.indexOf('PIN_')==0) return x[n]; return null; })(window).f.render.buttonPin(element);
</script>

물론 assets.pinterest.com/js/pinit.js 이 이미 페이지에 로드되어 있다고 가정합니다.렌더링 개체에는 buttonBookmark, buttonFollow, ebedBoard, inbedPin, inbedUser와 같은 다른 유용한 메서드가 있습니다.

저는 Derrek의 솔루션(그리고 선언되지 않은 변수 문제를 수정)을 기반으로 핀터레스트 버튼을 동적으로 로드하여 로드 시간을 늦출 수 없도록 했습니다.원래 질문과 관련이 있을 뿐이지만 어쨌든 공유해야겠다고 생각했습니다.

문서 끝:

<script type="text/javascript">
addPinterestButton = function (url, media, description) {
    var js, href, html, pinJs;
    pinJs = '//assets.pinterest.com/js/pinit.js';
    //url = escape(url);
    url = encodeURIComponent(url);
    media = encodeURIComponent(media);
    description = encodeURIComponent(description);
    href = 'http://pinterest.com/pin/create/button/?url=' + url + '&media=' + media + '&description=' + description;
    html = '<a href="' + href + '" class="pin-it-button" count-layout="vertical"><img border="0" src="http://assets.pinterest.com/images/PinExt.png" title="Pin It" /></a>';
    $('#pinterestOption').html(html);

    //add pinterest js
    js = document.createElement('script');
    js.src = pinJs;
    js.type = 'text/javascript';
    document.body.appendChild(js);
}
</script>

문서 준비 기능:

addPinterestButton('pageURL', 'img', 'description');//replace with actual data

핀터레스트 단추를 표시할 문서에서 ID가 pinterestOption인 요소를 추가합니다.

<div id="pinterestOption"></div>

누군가에게 도움이 되기를!

제가 한 일은 이렇습니다.

먼저 pinit.js를 보고 특별히 표시된 앵커 태그를 IFRAME으로 대체하기로 결정했습니다.생성된 iframes에서 src 속성이 사용하는 호스트 이름을 얻기 위해 Javascript 로직을 작성할 수 있다고 판단했습니다.

그래서 핀터레스트로 정상적인 추천에 따라 마크업을 넣었지만, 보이지 않는 디브에 앵커태그를 넣었습니다.

<div id='dummy' style='display:none;'>
<a href="http://pinterest.com/pin/create/button/?
    url=http%3A%2F%2Fpage%2Furl
    &media=http%3A%2F%2Fimage%2Furl" 
   class="pin-it-button" count-layout="horizontal"></a>
</div>
<script type="text/javascript" src="//assets.pinterest.com/js/pinit.js">
</script>

그리고 나서, 그 직후, 저는 삽입된 iframe에서 핀터레스트 CDN의 호스트 이름을 후루룩업하는 스크립트를 삽입했습니다.

//
// 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; i<L1; i++) {
            k.push(iframes[i]);
        }
        do {
            iframe = k.pop();
            src = iframe.attributes.getNamedItem('src');
            if (src !== null) {
                split = src.value.split('/');
                L2 = split.length;
                obj.host = split[L2 - 2];
                obj.script = split[L2 - 1].split('?')[0];
                //iframe.parentNode.removeChild(iframe);
            }
        } while (k.length>0);
    }

    spelunkPinterestIframe();

}(pinterestOptions));

그리고나서,

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 = '<iframe class="pin-it-button" ' + 'scrolling="no" ' +
        'src="//' + pinterestOptions.host + '/' + pinterestOptions.script +
        '?url=' + encodeURIComponent(pageUri) +
        '&media=' + encodeURIComponent(mediaUri);

    if (description === null) {
        description = 'Insert standard description here';
    }
    else {
        description = 'My site - ' + description;
    }

    pinMarkup += '&description=' + encodeURIComponent(description);
    pinMarkup += '&title=' + encodeURIComponent("Pin this " + tagType);
    pinMarkup += '&layout=horizontal&count=1">';
    pinMarkup += '</iframe>';
    return pinMarkup;
}

그런 다음 jQuery에서 다음과 같이 사용합니다.

    var pinMarkup = getPinMarkup("snap1.jpg", "Something clever here");
    $('#pagePin').empty(); // a div...
    $('#pagePin').append(pinMarkup);

FB와 유사하게 AJAX 콘텐츠 로드 후 Pinterest 태그의 구문 분석을 지원하기 위해 Pinterest 버튼 코드를 다시 작성했습니다.XFBML.parse() 또는 gapi.플러스 원. go.프로젝트의 대체 JavaScript 파일은 HTML5-유효한 구문을 지원합니다.

GitHub에서 PinterestPlus 프로젝트를 확인하십시오.

이를 위한 공식적인 방법은 스크립트를 로드할 때 "data-pin-build" 속성을 설정하는 것입니다.

<script defer="defer" src="//assets.pinterest.com/js/pinit.js" data-pin-build="parsePins"></script>

그런 다음 단추를 다음과 같이 동적으로 렌더링할 수 있습니다.

// render buttons inside a scoped DOM element
window.parsePins(buttonDomElement);

// render the whole page
window.parsePins();

사이트에는 스크립트 태그 없이 JavaScript로 렌더링할 수 있는 다른 방법도 있습니다.

여기 제가 한 일이 있습니다.AJAX 다시 로드 후 페이지의 여러 핀터레스트 버튼에서 작동하도록 @Derrick Grigg에 대한 약간의 수정.

refreshPinterestButton = function () {
    var url, media, description, pinJs, href, html, newJS, js;
    var pin_url;
    var pin_buttons = $('div.pin-it a');
    pin_buttons.each(function( index ) {
        pin_url = index.attr('href');
        url = escape(getUrlVars(pin_URL)["url"]);
        media = escape(getUrlVars(pin_URL)["media"]);
        description = escape(getUrlVars(pin_URL)["description"]);
        href = 'http://pinterest.com/pin/create/button/?url=' + url + '&media=' + media + '&description=' + description;
        html = '<a href="' + href + '" class="pin-it-button" count-layout="horizontal"><img border="0" src="http://assets.pinterest.com/images/PinExt.png" title="Pin It" /></a>';
        index.parent().html(html);
    });

    //remove and add pinterest js
    pinJs = '//assets.pinterest.com/js/pinit.js';
    js = $('script[src*="assets.pinterest.com/js/pinit.js"]');
    js.remove();
    js = document.createElement('script');
    js.src = pinJs;
    js.type = 'text/javascript';
    document.body.appendChild(js);
}

});


function getUrlVars(pin_URL)
{
    var vars = [], hash;
    var hashes = pin_URL.slice(pin_URL.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

이 게시물 http://dgrigg.com/blog/2012/04/04/dynamic-pinterest-button/ 을 읽어 보십시오. 이 게시물은 작은 자바스크립트를 사용하여 핀터레스트 iframe을 새 버튼으로 바꾼 다음 pinit.js 파일을 다시 로드합니다.아래는 트릭을 하기 위한 자바스크립트입니다.

refreshPinterestButton = function (url, media, description) {
    var js, href, html, pinJs;
    url = escape(url);
    media = escape(media);
    description = escape(description);
    href = 'http://pinterest.com/pin/create/button/?url=' + url + '&media=' + media + '&description=' + description;
    html = '<a href="' + href + '" class="pin-it-button" count-layout="horizontal"><img border="0" src="http://assets.pinterest.com/images/PinExt.png" title="Pin It" /></a>';
    $('div.pin-it').html(html);

    //remove and add pinterest js
    pinJs = $('script[src*="assets.pinterest.com/js/pinit.js"]');
    pinJs.remove();
    js = document.createElement('script');
    js.src = pinJs.attr('src');
    js.type = 'text/javascript';
    document.body.appendChild(js);
}

그들의 "Pinit" 버튼 문서에서 참조되는 pinit.js 파일은 글로벌을 노출하지 않습니다.한 번 실행되며 생성되는 iframe 이외의 추적을 남기지 않습니다.

새 단추를 "파싱"하기 위해 해당 파일을 다시 주입할 수 있습니다.그들의 JS는 실행될 때 모든 앵커 태그를 보고 그것들을 대체합니다.class="pin-it-button"그들의 iframe' 버튼으로.

이것은 나에게 잘 작동합니다: http://www.mediadevelopment.no/projects/pinit/ 클릭 이벤트에서 모든 데이터를 수집합니다.

Pinterest.init()에 전화를 걸어 페이지의 "새로운" 버튼(예: ajax'din, 동적으로 생성된 등)을 적절한 버튼으로 바꿀 수 있는 추가 사항을 추가하여 코드를 동일한 방식으로 작동하도록 조정하려고 했습니다.

프로젝트: https://github.com/onassar/JS-Pinterest 원시: https://raw.github.com/onassar/JS-Pinterest/master/Pinterest.js

2020년 6월 기준으로 핀터레스트는 핀 js 코드를 v2로 업데이트했습니다.따라서 데이터 핀 구축이 작동하지 않을 수 있습니다.<script defer="defer" src="//assets.pinterest.com/js/pinit.js" data-pin-build="parsePins"></script>

이제 pinit_v2.js에서 작동합니다.<script async defer src="//assets.pinterest.com/js/pinit_v2.js" data-pin-build="parsePins"></script>

언급URL : https://stackoverflow.com/questions/9352021/how-can-i-rerender-pinterests-pin-it-button

반응형