简体   繁体   中英

Detecting & displaying links in a form's text area

When I enter a link (video, image, URL, etc.) in Facebook's "What's on your mind?" form, it auto-detects the link and converts it to a thumbnail with a brief description below the text-area. Can anyone provide me with insight or a link to get me going on how to achieve this?

There's a javascript attached to the textarea change event. The javascript detects if the content of the textarea is a url, if it is, the javascript call a webservice that visit the url looking for the page title, the page description, etc, (or the open graph protocol meta tags), if it find each one of the tags they are returned to the javascript who proper organize then.

Facebook also cache this content, and if the same url is posted by another user, he uses the cache values instead of revisiting the page.

The open graph protocol meta tags:

http://developers.facebook.com/docs/opengraphprotocol/

using something like

var input = document.getElementById("textarea");
input.addEventListener("change", checkLink(e));
input.addEventListener("blur", checkLink(e));

function checkText(text){
     var exp = "((ht|f)tp(s?))(:((\/\/)(?!\/)))(((w){3}\.)?)([a-zA-Z0-9\-_]+(\.(com|edu|gov|int|mil|net|org|biz|info|name|pro|museum|co\.uk)))(\/(?!\/))(([a-zA-Z0-9\-_\/]*)?)([a-zA-Z0-9])+\.((jpg|jpeg|gif|png)(?!(\w|\W)))";
     return text.match(exp);
}
function checkLink(e){
     //here you would want to use a regular expression and check for http:

     var regularExpression = !!checkText(e.target.innerHTML); // returns true or false
     if(regularExpression){
       e.target.innerHTML += "<a href='#'><img src="" alt="" /></a>";
     }
}

good resource for regular expressions - http://regexlib.com/Search.aspx?k=image&c=-1&m=-1&ps=20

Warning -- have to leave for work so regular expressions are not checked.

Take the link value and run it through a regular expression that looks for ^http:...[^\\s] or ^https:...[^\\s] and returns those.

Then, pass those URLs to your server and have your server retrieve the document and return a snippit for you to then put in your document. You must have your own server to help because Javascript, by itself, has security restrictions. Google same origin policy for more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM