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.
Related
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);
that is we have opened many tabs.In that tabs i want to search specific tab. Please tell if any ext or option or add-on in chrome or firefox.
Firefox has this functionality built in. If you just start typing in the URL bar and the first character you type is % followed by a space, the rest of what you type will be treated as a search on the titles and urls of open tabs in all Firefox windows.
I'm not sure if this is the site to be asking for help finding extensions that do end user tasks such as this so I'll answer your question explicitly as well as explain how to do it programatically.
The short answer is, yes one extension that will allow you to do this can be found here:
Tab Title Search
The long answer is, in order to find all tabs with a certain name, you need to use the chrome tabs API
I whipped up a short piece of javascript to demonstrate how to have an extension that will create a popup with a search box that you type the desired tab title into. If the tab is found, it will be listed below the search box. If you click on the listing, you will switch to the tab.
// Function to search for tabs
function searchtabs() {
chrome.tabs.query({
title: ""
},
// Callback to process results
function(results) {
// Place holder for the tab to process
var foundTab = null;
// Text to match against
var queryText = document.getElementById("textToSearchInput").value;
// Div to place divs of matched title in
var queryAnswerDiv = document.getElementById("foundTabsDiv");
// Clear the current children
while (queryAnswerDiv.hasChildNodes()) {
queryAnswerDiv.removeChild(queryAnswerDiv.lastChild);
}
// Iterate over all the results
for (var i = 0; i < results.length; i++) {
// Keep track of the tab that is currently being processed
foundTab = results[i];
// If we have a title containing our string...
if (foundTab.title.indexOf(queryText) > -1) {
// Create a new div
var tabDiv = document.createElement("div");
// Set its content to the tabs title
tabDiv.innerHTML = foundTab.title;
// Let it know what the tabs id is
tabDiv.tabToSwitchTo = results[i].id;
// Allow for users to click on the representing div to switch to it
tabDiv.onclick = function() {
// Make the tab selected
chrome.tabs.update(this.tabToSwitchTo, {
selected: true
});
};
// Append the created div to our answer div
queryAnswerDiv.appendChild(tabDiv);
}
}
});
}
document.addEventListener('DOMContentLoaded', function() {
var inputField = document.getElementById("textToSearchInput");
inputField.focus();
inputField.onkeydown = searchtabs;
});
Also, if this is more what you are looking for rather than the extension that I linked, let me know and I can pack this extension.
Edit:
Fixed an error in using the wrong ID to get the input field as well as not getting the first letter of the title (use indexOf() > -1)
An extension that does this is Tab Hero for Chrome ($0.99 Chrome extension). It searches through all of the open tabs (across multiple windows) and offers to switch to the filtered tab. Try and see if it works for you.
Is it possible to selectively remove items from Google Chrome browsing history? I have a website from my history that wants to be the default everytime I start a search with a specific letter, but I often reference my history to re-find things.
So I would like to remove all history from, say, www.pythonismyfavoritest.com without removing everything; is that possible?
Try searching www.pythonismyfavoritest.com in the search bar in chrome://history/ and then remove each item by clicking the check box in the left and then hitting the "remove selected items" button.
The chrome history api works with url such chrome://history/#q=hello&p=0
Here's something I wrote in JavaScript. It works through the Console Debugger. I tried using it in a bookmark but I get no response from the page.
** // UPDATE (07.28.15)
I added a shorter approach provided by #Denis Gorbachev to the checkbox targeting, which helped shorten some of this code. I also added "auto-stop" functionality, meaning the loop will stop once it has finally cleared the list.
** // UPDATE (08.20.14)I made a few changes to the code, to make it more user friendly. Other users may not be code-savvy, and others may simply prefer convenience. Therefore, I whipped up a couple buttons (start/stop) to control the usage; as well as address some "ASSERTION FAILED" exceptions/errors that were being thrown when attempted to run the script loop.. Enjoy!!
In your address bar, type in the following address to to the meat of the history page.. It's normally loaded in an iframe, with the left-side menu loaded in another frame.. // **
chrome://history-frame/
Next, load your Console Debugger/Viewer by pressing Ctrl+Shift+J(For Mac users, ⌘+⌥+J)
You can also press F12 and select the "Console" tab.
In the Console Debugger/Viewer, copy & paste the following code:
function removeItems() {
removeButton = document.getElementById('remove-selected');
overlayWindow = document.getElementById('overlay');
//revision (07.28.15): Replaced the For Loop targeting the checkboxes, thanks to Denis Gorbachev via comments (02.19.15)
Array.prototype.forEach.call(document.querySelectorAll("input[type=checkbox]"), function(node) {node.checked = "checked"})
setTimeout(function () {
if (removeButton.getAttribute("disabled") !== null) {
removeButton.removeAttribute("disabled")
}
/* revision (08.20.14): no longer binding to that condition, button should no longer be disabled, so click! */
if ((overlayWindow.hasAttribute("hidden")) && (overlayWindow.getAttribute("hidden") !== false)) {
removeButton.click();
}
/* revision (08.20.14): new Interval, to check against the overlay DIV containing the confirmation "Remove" button */
/* Attempting to click the button while the DIV's "hidden" attribute is in effect will cause FAILED ASSERTION */
stopButton = setInterval(function () {
if (overlayWindow.hasAttribute("hidden")) {
if (overlayWindow.getAttribute("hidden") == "false") {
hidden = false
} else {
hidden = true
}
} else {
hidden = false
}
if (!hidden) {
document.getElementById("alertOverlayOk").click();
clearInterval(stopButton)
}
}, 250)
}, 250)
}
//revision (08.20.14): Lets build our buttons to control this so we no longer need the console
//stop button (08.20.14)
var stopButton = document.createElement('button');
stopButton.setAttribute('id', "stopButton");
stopButton.innerHTML = "Stop";
stopButton.style.background = "#800";
stopButton.style.color = "#fff";
stopButton.style.display = "none";
stopButton.onclick = function () {
clearInterval(window.clearAllFiltered);
document.getElementById("stopButton").style.display = "none";
document.getElementById("startButton").style.display = ""
};
//start button (08.20.14)
var startButton = document.createElement('button');
startButton.setAttribute('id', "startButton");
startButton.innerHTML = "Start";
startButton.style.background = "#090";
startButton.style.color = "#fff";
startButton.onclick = function () {
window.clearAllFiltered = setInterval(function () {
/* revision (07.28.15): Stop the Loop automatically if there are no more items to remove */
if(document.getElementById("results-header").innerText=="No search results found."){
document.getElementById("stopButton").click();
}
if (document.getElementById("loading-spinner").getAttribute("hidden") !== null) {
removeItems()
}
}, 250); //adjust Time Here (1500 [millisec] = 1.5sec)
document.getElementById("stopButton").style.display = "";
document.getElementById("startButton").style.display = "none"
};
/* revision (08.20.14): Now we add our buttons, and we're ready to go! */
editingControls = document.getElementById('editing-controls');
editingControls.appendChild(stopButton);
editingControls.appendChild(startButton);
This removeItems function will select loop through all form inputs and check all checkboxes, enable the "Remove Selected Items" button and click it. After a half-second, it'll check if the "Are You Sure" prompt is displayed and, if so, click the "Yes/Remove" button automatically for you so that it will load a new list of items to do this process all over again..
The item is looped using the variable "clearAllFiltered", which is a setInterval loop, which is checking for the status of the "Loading" screen..
To start erasing your filtered history items, you can now click the green Start button.
** // UPDATE (07.28.2015) It will now stop on ITS OWN.
To stop the loop manually, you can now click the red Stop button. Simple as that!
1) Go to your history settings ( chrome://history/ )
2) In the top right hand corner will be a search bar with a 'Search History" button
3) Type in the sitename you want to remove from history, then click the button
4) Click the box on the first one, then scroll to the bottom of the page
5) Press and hold the Shift key, then click the last box (This will check all on that page)
6) Scroll back up and select the 'Remove Selected Items" Button
7) Repeat steps 4-6 until all your Youtube History is gone.
Hopefully Chrome will update this clear history feature, but for now this seems to be the fastest option
Easy way is Shift+Delete.
For example when you type "you", "youtube.com" will be shown as selected in suggestions. Just click Shift+Delete. Then retype "you" and you will see no "youtube.com" in that list anymore.
If you are talking about getting rid of the suggested search/auto-completion... then removing specific items from your chrome://history won't do it (in my experience). I want to fill in more detail to the answer #LacOniC gave.
In the screenshot you can see I typed "ba" and Chrome is suggesting completion based on my browsing history (the items in green).
In my experience, removing specific items from your history will not remove them from showing up in this address bar auto-completion.
To quickly remove these auto complete items:
Start typing a few letters that generate the offending suggestion.
Use your keyboard's arrow keys to select the suggestion you don't like (selected item is highlighted blue in screenshot).
Press shift+delete on windows or shift+fn+delete on mac to remove the selected item.
Is it possible to send the server only the last 3 words in the textarea and to autofill the best result, letting the user keep typing in (similar to Google auto complete)?
I want the behavior to be:
N[ew]
New[er]
New(SPACE)[er]
New [York]
New c[ar]
New cat [food]
New cat (TAB) [food]
New cat food [makes]
...
New cat food is good for your cat's [health]
(clarification: the [square brackets] indicates the suggestion that is automatically being typed in, the bold text indicates the part being sent to the server, (TAB) and (SPACE) indicates tab and space key presses)
I already a have function on the server for predicting the next word (using Markov chains) and I have integrated jQuery UI autocomplete, but currently it just sends all the text to the server and creates a list with all the suggestions to choose from, once you choose it changes the whole text.
So it eventually comes to these issues:
How to send only the last part?
How to append + select the suggested word?
How to select on Tab key?
Okay - here is the solution (and here is the result):
1 + 2: Instead of managing a single input box, I use two identical size textarea's, the first (#text-area) is enables and with transparent background and the other (#suggestions) is disabled and with gray text color. I use the source callback to do all the work:
$('#text-area').autocomplete({ ...
source: function( request, response ) {
if (request.term.length < 3) {
return false;
}
$.getJSON( $SCRIPT_ROOT + '/_get_word', {
term: request.term
}, function(data) {
$('#suggestions').val(data.result) //suggestion is the disabled textarea
}
);
return false;
},
...
});
});
3: the tab key selection is done with triggering the autocomplete search event:
$('#text-area').live( "keydown",'textarea', function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB) {
event.preventDefault();
$('#text-area').val($('#suggestions').val());
$("#text-area").autocomplete('search', $('#text-area').val());
}
});
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);
}