How Facebook link preview happens?
Aside from that, it's fairly simple: use an HTTP client library for your language of choice to connect to the provided URL, then use an HTML parsing library to extract the title tag, identify a significant piece of text in the body tag, and extract the img tag sources that seem the most appropriate.
Once your server is able to extract information about a page, it's a fairly simple exercise to call it through AJAX.
I developed myself a Facebook Link Preview with PHP and jQuery that is on my website. Take a look... The source code is free... I didn't post the whole code here because they are many files... But if you prefer the code to be posted here, tell me and I'll post.
It's available on Github https://github.com/LeonardoCardoso/Facebook-Link-Preview
I think following steps are involved
- From the found links get the last link in the text (FB shows only for last link)
- Using AJAX send this link detail to a server side page (PHP/ASP/JSP etc.)
- The server side page gets the required data (from Meta tags) including
- Title (Preferably Open graph og:title if missing from <title>
- Description (Preferably Open graph og:description if missing from <meta name="description" ....
- Images (Preferably Open graph og:image if missing from <img src=....
- In PHP you can get these datas either using curl or file_get_contents and parse for required data detailed above. Not sure about other Language.
- Show the result thus found in the AJAX request.
Additionally I think FB stores the data, once found, in database and 1st queries there. This helps them to get faster result and hence same article shared and liked generate the image and details from the stored data.
Surprisingly there aren’t that many services out there doing this. As the previous commenter posted, your browser can’t do this without a server element.
So, the workflow is really this:
- Parse the inserted text to test it’s a valid URL
- Whiz that URL value via AJAX to a bespoke service or roll your own.
- The service (mine is written in .Net) loads up the page in memory and parses it with an DOM parser. I use the HTML Agility pack you could use AngleSharp etc.
- You need to extract the Open graph meta elements with (typically) fall back to standard Meta Title/ Description et all.
- Pack up all that OG goodness and return this model via AJAX
- Put the returned values on screen as a preview.
- If accepted write the logic to insert the values into your DB
If you are not up to creating the server object, there are third-party services that can do the retrieval bits:
best of luck.