Tweet clickable links on website? - html

Right, based on this question Tweet clickable links with twitteroauth?,
How do I actually parse the entire string and replace the t.co link portion with a
portion?
For example i tweet this -
Hey check out this link www.google.com
and in my website currently it shows
Hey check out this link http://t.co/generatedlink
So how do i parse it and make it into this
Hey check out this link http://t.co/generatedlink
which would display like this in my website:
Hey check out this link http://t.co/generatedlink
How am I able to detect that a certain portion of the tweet text has a link inside it? Or am I going about this wrong?

You need to understand Twitter Entities.
When you request the tweet, make sure you use include_entities=true
For example:
https://api.twitter.com/1/statuses/show.json?id=220197158798897155&include_entities=true
In the response, you will see an element called "entities" inside that, you will see "urls".
That will contain all the URLs and their position (indices) within the tweet.
"text": "Twitter for Mac is now easier and faster, and you can open multiple windows at once http://t.co/0JG5Mcq",
"entities": {
"urls": [
{
"url": "http://t.co/0JG5Mcq",
"display_url": "blog.twitter.com/2011/05/twitte…",
"expanded_url": "http://blog.twitter.com/2011/05/twitter-for-mac-update.html",
"indices": [
84,
103
]
}
],
}

function urlify(text) {
var urlRegex = /(https?:\/\/[^\s]+)/g;
return text.replace(urlRegex, function(url) {
return '' + url + '';
})}
var text = "Hey check out this link http://t.co/generatedlink";
var a = urlify(text);
alert(a);
The above solution is perfect for your needs. I have a Fiddle link too Check it out http://jsfiddle.net/UhzCx/
I got this answer here Detect URLs in text with JavaScript

If you can use javascript, here is an example http://jsfiddle.net/3VF96/13/
Function
function generateURL(text){
var str=text;
var n=str.indexOf("http");
var strv=str.substring(0,n);
var link=str.substring(n,str.length);
strv=strv+" <a href='"+link+"'>"+link+"</a>";
$("#Link").append(strv);
}
​

Related

Using a bot to open embed hyperlinks sent in a discord channel by another bot

Situation: 3rd Party Discord Bot sends masked URL in case of certain events into a private discord channel as an embedded message, instead of clicking on them manually the goal is to have another bot opening those hyperlinks automatically.
Current Status: With a lot of research (also on stack overflow) I managed to get to the following state that will open hyperlinks that are sent as normal text in the respective discord channel or that are included in the description of an embedded message (Kudos to Zach C & Daemon Beast):
client.on("message", message => {
if (message.channel.id == config.channelIds) {
//first part analyses normal messages
if (message.content.includes("https")) {
var link = message.content.split("https")[1]
console.log(link)
var linktest = `https${link}`
console.log(`opening ${linktest}`)
open(linktest)
}
//second part analyses embeded messsages
else if (message.embeds) {
message.embeds.forEach(embed => {
if (embed.description.includes("https")){
var link = embed.description.split("https")[1];
link = link.replace(")", "");
console.log(link);
var linktest = `https${link}`;
console.log(`opening ${linktest}`);
open(linktest);
}
});
}
}
})
Testing: Testing was done using another Bot sending embedded hyperlinks. When they were embedded in the Body/Description the hyperlinks are being opened just fine.
//Testing Bot:
{"content": null,
"embeds": [
{
"title": "Test Title",
"description": "Test Description",
"color": 2108322,
"fields": [
{
"name": "Test Name",
"value": "Test Value\n[Click here to test](https://google.com)"
}]}]}
Problem: In this particular use case hyperlinks are not included in the body/description but rather in the field value which currently not being recognized by the bot and thus not opened.
I already went tough a couple of hours of research & trial/error but was not able to change the code in a way that it would work.
I have tried to use "some" functionality
if (embed.fields.some(f => f.value.includes("https")))
and "includes"
if(message.content.toLowerCase().includes("https"))
But while with the some functionality I was able to make some progress by getting a return value "true" I struggle in adjusting the "var link =" in a way to then get to a proper link.
I have used the replace function to remove the closing bracket ) from the hyperlink.
I feel like I have reached 95% and there is only a small adjustment necessary that the code actually targets the right fields in the embedded message.
Your support is very much appreciated, thank you in advance!
For the sake of completion I would like to share the found solution, there would be better ones with loops but this one worked for me as the link is always at the same place in the embed:
else if (message.embeds) {
message.embeds.forEach(embed => {
console.log(message.embeds[0].fields[8].value);
if (embed.fields[6].value.includes("https")){
var link = embed.fields[6].value.split("https")[1];
link = link.replace(")", "");
console.log(link);
var linktest = `https${link}`;
console.log(`opening ${linktest}`);
open(linktest);

chrome selection text to keep formatting

I have a context menu, so when you selection some text from a page they can send to my extension. I am using
var child1 = chrome.contextMenus.create(
{"title": "Send To Box" , contexts:["selection"], "parentId": id, "id":"box", "contexts":[context], "onclick": sendToMyBox});
And in my sendToMyBox
function sendToMyBox(info, tab)
{
if (info.menuItemId == "box")
{
mainData = info.selectionText;
}
}
So the issue is selectionText is missing all the formatting. What ever selected its coming as a single line text, is there anyway I can get the current format from the selected. Basically I want to keep all the new lines tabs, etc...
Thanks
I think maybe you can get the html element first (you can achieve that by register a mouse event, then get event.target), then use
element.innerHTML
to get the rich text.

Ext JS 4.2 metadata tpl not recognized

First time, long time...
I am using Ext JS 4.2.2.1144
I have a grid and my query from the server(php) is returning metadata in the form of json that was previously generated when a user decides to realign and resize the columns and then save that information. All of the fields like width, dataIndex, align, and all that are reconfiguring the grid just fine when using the metaChanged function. The problem that I am having is that one of the columns needs to send over the information for a tpl which is actually the location of an image to show. My Json looks like this
{
"totalCount":"2",
"root":"items",
"metaData":
{
"fields":[
{"name":"queryid"},
{"name":"createUser"},
{"name":"subject"},
{"name":"priorityImage"}
],
"columns":[
{
"dataIndex":"queryid",
"width":100,
"text":"Queryid"
},
{
"dataIndex":"createUser",
"width":100,
"text":"Owner",
"align":"center"
},
{
"dataIndex":"subject",
"width":200,
"text":"Subject",
"hidden":true
},
{
"dataIndex":"priorityImage",
"width":70,"text":"Priority",
"hidden":true,
"align":"center",
"xtype":"templatecolumn",
"tpl":['<img src="_images/{priorityImage}" height="20px" width="20px" />']
}
]
},
"items":[
{
"queryid":"1",
"createUser":"1",
"subject":"Here is a new project",
"priorityImage":"orange.png"
},
{
"queryid":"1",
"createUser":"1",
"subject":"SAL Form 4",
"priorityImage":"roundlightPurple.png"
}
]
}
I have tried all kinds of different ways of sending the tpl for this last column but none of them are success. Anybody with any clues on how to accomplish this? The result ends up being the text and not the actually image. If I load the grid directly from the store using the default model, I get the image from the tpl but just not when doing it through metadata. I have tried single quotes, double quotes, no braces, with braces, lol. Im out of ideas to try. Hopefully I am being clear enough. Anyhoo, thanks for any help in advance, this one is really driving my crazy,
thanks,
C5
I have done something similar long time ago when I needed to send renderers (functions) but they always appear as text. At that time I haven't found other way but to scan the received metaData to see if there is a renderer and call eval on the received text to get the function.
Although not a "do this" answer, I hope it helps.
I figured a work around for this although maybe not the most ideal solution it does work.
When sending the tpl to the Server, it actually gets translated from
<img src="_images/{priorityImage}" height="20px" width="20px" /> to
<img src="_images/{priorityImage}" height="20" width="20" />
So here is my fix for now anyway:
Before I call the code to load the store
Ext.getCmp('lblCurrentMetaGrid').setText('projectsGridGrid');
store.on('metachange', metaChanged, this);
Then in the metaChanged function it looks like this:
function metaChanged(store,meta){
var gridname = Ext.getCmp('lblCurrentMetaGrid').text;
var grid = Ext.getCmp(gridname);
for(var c = 0; c < meta.columns.length; c++ ){
var column = meta.columns[c];
var tpl = column.tpl;
if ( tpl !== undefined){
meta.columns[c].tpl[0] = meta.columns[c].tpl[0].replace('<','<');
meta.columns[c].tpl[0] = meta.columns[c].tpl[0].replace('>','>');
meta.columns[c].tpl[0] = meta.columns[c].tpl[0].replace(/\"/g,'"');
}
}
//lets look at all the metadata
grid.reconfigure(store,meta.columns);
}
Now, I am getting my image in the grid.

How to populate a jQuery Mobile ListView with JSON data?

I'm developing a webapp here using HTML and jQuery Mobile (JQM), so I'm pretty new at this.
What I'm trying to do here is to populate a JQM listview with a list of names.
Each of this names will link to a new page with personal data being displayed (Full name, address, date of birth, etc).
Currently, because of my lack of knowledge, I manually create a new .html file for EACH individual person (e.g. johnDoe.html for a fictional character Mr. John Doe). I then physically link the list elements to this html file via the function.
Problem is now I have 100 over individuals to populate that list view. I think that there's an easier way to do this rather than manually creating 100+ html files for all these individual persons right?
I heard of this JSON thing that might do the trick, but coming from a background of ZERO computing knowledge, I don't really understand how it works. Will someone please shed some light on how can I do this?
Thanks a lot!
EDIT:
I'm using Dreamweaver CS5.5 to do the coding. For this webapp that I'm tasked to develop, I was given a "template" or sorts that uses JQM and Backbone.js. As such, somehow the "multi-page" structure for a single HTML file doesn't seem to work. From what I see in the template, every HTML file has a corresponding JS file that has code that looks like this:
define(['jquery',
'underscore',
'backbone',
'helper',
'views/phr/list',
'text!templates/vpr2.html'
],
function ($,
_,
Backbone,
Helper,
phrListView,
tmpVpr2) {
var view = Backbone.View.extend({
transition: 'fade',
reverse: true,
initialize: function () {
this.phrlistview = new phrListView();
},
render: function () {
$(this.el).append(_.template(tmpVpr2, {}));
console.log("Rendering subelements...");
Helper.assign(this, {
'#phrListView': this.phrlistview
});
return this.el;
}
});
return view;
});
For the HTML pages, they all begin with a <div data-role=header> tag, then a <div data-role=content>, before ending with a <div data-role=footer>, all with their respective content within the opening and closing tags.
For my listview in question, the JQM code for the listview will be within the <div data-role=content> part of the HTML file. How can I populate this listview with JSON data then?
(Apologies if I sound extremely noob at this, because I really am >.< Really appreciate the help!)
Solution
Yes. Its possible to have two pages and use one for displaying your data and one to show up the details of the clicked item. I had to pull in some old stuff, a demo I made when jQM was in version 1.1 and change it to modern times. Anyway, considering I have an array like this :
[
{
"id": 0,
"age": 31,
"name": "Avis Greene",
"gender": "female",
"company": "Handshake",
"email": "avisgreene#handshake.com",
"phone": "+1 (845) 575-2978",
"address": "518 Forrest Street, Washington, New York, 3579"
},
{
"id": 1,
"age": 31,
"name": "Dunn Haynes",
"gender": "male",
"company": "Signity",
"email": "dunnhaynes#signity.com",
"phone": "+1 (829) 454-3806",
"address": "293 Dean Street, Dante, Oregon, 5864"
}
]
I randomly generated stuff and made it upto 100 elements, just like how you seem to have. I have two pages.
<!--first page -->
<div data-role="page" id="info-page">
<div data-role="header" data-theme="b">
<h1> Information</h1>
</div>
<div data-role="content">
<ul data-role="listview" id="prof-list" data-divider-theme="a" data-inset="true">
<li data-role="list-divider" data-theme="b" role="heading">Names</li>
</ul>
</div>
</div>
<!--second page -->
<div data-role="page" id="details-page">
<div data-role="header" data-theme="b">Go back
<h1>Employee Details</h1>
</div>
<div data-role="content"></div>
</div>
The first page, #info-page is for showing data in a listview. The second page, #details-page is for the info of the clicked item. Thats all you need. Only two pages, not more than that. So every time a click happens, you do the following through JavaScript
Get the current value of data from the array. Like if you click on the 4th li in the list, get the 4th object from the array which has all the data.
Store it in the data variable of the second page, so that it can be retrieved later. Something like this:
$("#details-page").data("info", info[this.id]);
Then, redirect to second page using changePage, like this :
$.mobile.changePage("#details-page");
When the second page opens, use the pagebeforeshow event to get the data from the page (which you stored into this page when the tag in the previous page was clicked.
Use some HTML layout to populate the data. I used jQM's grids.
That's all folks!
Full code
Ive attached the JS used with the HTML. Its self explanatory. Read the inline comments in the code and you'll be able to understand more. Assume info is the array in picture.
//pageinit event for first page
//triggers only once
//write all your on-load functions and event handlers pertaining to page1
$(document).on("pageinit", "#info-page", function () {
//set up string for adding <li/>
var li = "";
//container for $li to be added
$.each(info, function (i, name) {
//add the <li> to "li" variable
//note the use of += in the variable
//meaning I'm adding to the existing data. not replacing it.
//store index value in array as id of the <a> tag
li += '<li>' + name.name + '</li>';
});
//append list to ul
$("#prof-list").append(li).promise().done(function () {
//wait for append to finish - thats why you use a promise()
//done() will run after append is done
//add the click event for the redirection to happen to #details-page
$(this).on("click", ".info-go", function (e) {
e.preventDefault();
//store the information in the next page's data
$("#details-page").data("info", info[this.id]);
//change the page # to second page.
//Now the URL in the address bar will read index.html#details-page
//where #details-page is the "id" of the second page
//we're gonna redirect to that now using changePage() method
$.mobile.changePage("#details-page");
});
//refresh list to enhance its styling.
$(this).listview("refresh");
});
});
//use pagebeforeshow
//DONT USE PAGEINIT!
//the reason is you want this to happen every single time
//pageinit will happen only once
$(document).on("pagebeforeshow", "#details-page", function () {
//get from data - you put this here when the "a" wa clicked in the previous page
var info = $(this).data("info");
//string to put HTML in
var info_view = "";
//use for..in to iterate through object
for (var key in info) {
//Im using grid layout here.
//use any kind of layout you want.
//key is the key of the property in the object
//if obj = {name: 'k'}
//key = name, value = k
info_view += '<div class="ui-grid-a"><div class="ui-block-a"><div class="ui-bar field" style="font-weight : bold; text-align: left;">' + key + '</div></div><div class="ui-block-b"><div class="ui-bar value" style="width : 75%">' + info[key] + '</div></div></div>';
}
//add this to html
$(this).find("[data-role=content]").html(info_view);
});
Demo
I've also made a demo where you can read more about this at jsfiddle.net.
Here's the link : http://jsfiddle.net/hungerpain/52Haa/
you can try something like this
Updated
Html Page
<div data-role="page" id="testpage">
<div data-role="content">
<ul data-role="listview" id="listitem" data-divider-theme="a" data-inset="true">
</ul>
</div>
</div>
javascript
$(document).on("pageinit", "#testpage", function(){
$.getJSON("example.json", function(data){
var output = '';
$.each(data, function(index, value){
output += '<li>' +data+ '</li>';
});
$('#listitem').html(output);
});
});

Chrome extension WebNavigation API getFrame

I found a chrome extension WebNavigation API, but I don't know how to use it. Could someone give me a simple example?
API:
chrome.webNavigation.getFrame(object details, function callback)
If I want to get iframe id and iframe's scr in a page, can I use this API ??
As the docs state, one needs to pass tabId, processId, frameId...
in order to get these values, one needs to listen for .onCompleted():
chrome.webNavigation.onCompleted.addListener(function(e){
chrome.webNavigation.getFrame(
{tabId: e.tabId, processId: e.processId, frameId: e.frameId},
function(details){
console.dir(details);
}
);
});
The event's properties are already known before the .getFrame()
If you want to access page content you should use content scripts
So, for example in the manifest.json:
{
"name": "My extension",
...
"content_scripts": [
{
"matches": ["http://www.example.com/*"],
"js": ["jquery.js", "myscript.js"]
}
],
}
And in myscript.js:
var iframe = document.querySelector('iframe');
alert(iframe.getAttribute('id'), iframe.getAttribute('src'));
Another way is to use programmatic injection which is in fact simplified content scripting.
Update:
To get src from all iframes on the page:
var iframes = document.querySelectorAll('iframe');
for(var i = 0; i < iframes.length; i++){
console.log(iframes[i].getAttribute('id'), iframes[i].getAttribute('src'));
}