Google's +1 Button: How do they do it?

前端 未结 3 773
耶瑟儿~
耶瑟儿~ 2021-02-01 22:34

Exploring Google\'s +1 Button, I found two things odd about the code they supply:



        
相关标签:
3条回答
  • 2021-02-01 23:01

    The first trick is interesting. It looks like a creative way to pass "global" arguments from the page markup to external scripts. There are ways to find the <script> element that sources the code that's currently running, and I would not be surprised if the inner text of that <script> element was accessible from the DOM even though the browser ignores it.

    In your question, this pattern allows each external client-side script to use (at least) its own localization settings, and also allows server-side code to render that parameter as a side effect of rendering the <script> element itself. That's impressive.

    The second trick, I'm not so sure about. Basically, I think most browsers would consider the namespaced <g:plusone> element as unknown or even invalid, so they should render its content, but it won't do anything, of course, since that element is empty to begin with.

    However, client-side code might still be able to match the namespaced element using DOM navigation, and replace it with its own generated content.

    0 讨论(0)
  • 2021-02-01 23:07

    Is the syntax <g:plusone ... HTML valid?

    No

    What's this called?

    Invalid psuedo-namespaces

    0 讨论(0)
  • 2021-02-01 23:14

    How is Google able to use the text between the script tags?

    <script> elements are perfectly visible in the DOM:

    <script type="text/javascript">//FIRST SCRIPT BLOCK</script>
    
    <script type="text/javascript">
        var s= document.getElementsByTagName('script')[0];
        alert(s.textContent); // "//FIRST SCRIPT BLOCK"
    </script>
    

    Google's sneaky trick is to put content in a <script> that has an external src. In this case the src overrides the content inside the block and executes the external script instead, but the contents of the <script> element are still readable through the DOM even though they do nothing.

    Is the syntax <g:plusone ... HTML valid? What's this called?

    No. If they made their own doctype for HTML+plusone it could be valid that, but it doesn't satisfy validity for HTML, and it isn't even namespace-well-formed in an XHTML document, unless you add an extra xmlns:g for it too.

    0 讨论(0)
提交回复
热议问题