Chrome Extension: contextMenus.create: Invalid url pattern - google-chrome-extension

Trying to make a very simple Chrome extension. If someone right clicks on a subreddit link, there is a context option to send it to redditp.com instead.
background.js
{
function redpts(info,tab) {
var url = info.linkUrl;
console.log("Link " + info.selectionText + " was clicked to be redditp'd.");
var urlp = url.replace(/reddit.com/i, "redditp.com");
chrome.tabs.create({ url: urlp });
}
chrome.contextMenus.create({
"title" : "RedditP That Shizz!",
"type" : "normal",
"contexts" : ["link"],
"targetUrlPatterns": ["*://*reddit.com/r*"],
"onclick" : redpts
});
}
The error chrome throws is that I have not pattern matched the subreddit URL properly, but I very much tried to follow the formatting instructions of the 'Match Patterns' google page.
Full Error: Unchecked runtime.lastError while running contextMenus.create: Invalid url pattern '*://*reddit.com/r*'
I am a bit cross-eyed trying to see my mistake. Thanks.
Edit: If I comment out the targetUrlPatterns, it works as expected.

Your url pattern should be
"*://*.reddit.com/r*
and you context menu for new chrome version look like be
chrome.contextMenus.create({
"id" : "someuniquerid",
"title" : "RedditP That Shizz!",
"type" : "normal",
"contexts" : ["link"],
"targetUrlPatterns": ["*://*.reddit.com/r*"]
});
chrome.contextMenus.onClicked.addListener(function(e){
if(e.menuItemId == 'someuniquerid') {
chrome.tabs.getSelected(function(tab){
// do you work here
});
}
});

Related

Microsoft Bot Framework - giving blank spaces

How to give a blank space after writing some text in session.send();
For example,
session.send('Low : 1<br/><br/>Medium : 2<br/><br/>High : 3<br/><br/>Urgent : 4');
Should give output as
Low : 1
Medium : 2
High : 3
Urgent : 4
Link 1 I've gone through this, but it's relevant for what I am searching for
Here's the code and the screenshot
(session, args) => {
session.dialogData.Email = args.response;
builder.Prompts.text(session, "Set Priority");
const msgText = `Low : 1\n\nMedium : 2\n\nHigh : 3\n\nUrgent : 4`;
const msg = new builder.Message(session).text(msgText).textFormat('markdown');
session.send(msg);
},
Depending on the channel you can use Markdown syntax. Here is an example.
const msgText = `Low : 1
Medium : 2
High : 3
Urgent : 4`;
const msg = new BotBuilder.Message(session)
.text(msgText)
.textFormat("markdown");
session.send(msg);
For Markdown support check the channel inspector here. Actually with markdown you can do more.
I have updated the code to use pre tags. Does that help?
Updated once again. Following is the output:
===================
Although I think the functionality you are trying to achieve can be better achieved by utilizing BotBuilder Prompts library. Here is a sample:
bot.dialog("/", [
function(session) {
BotBuilder.Prompts.choice(
session,
"Select your option: ",
["Low", "Medium", "High", "Urgent"],
{ listStyle: BotBuilder.ListStyle.button }
);
},
function(session, result: any) {
session.send(
`You selected ${result.response.index}: ${result.response.entity}`
);
session.endDialog();
}
]);
Utilizing BotBuilder.Prompts library will also help in validation as the validation for selected option is built into the library, and if user has entered something giberish, the library auto-prompts by itself. Output:

How to use objects inside res() in Node.js?

When I tried giving like this, it says error
temaplateObj.name: obj.name,
^
SyntaxError: Unexpected token .
My code:
var temaplateObj = {};
res.render('modules/users/server/templates/getdeals', {
temaplateObj.name: obj.name,
temaplateObj.from: common.tokenInfo.name,
temaplateObj.appName: 'GAIPP',
temaplateObj.company: company,
temaplateObj.logo: logo,
temaplateObj.url:url
},
I am not sure how to assing values to an obj inside res({}). Can any one suggest help?
Just pass a valid object to res.render():
res.render('modules/users/server/templates/getdeals', {
name : obj.name,
from : common.tokenInfo.name,
appName : 'GAIPP',
company : company,
logo : logo,
url : url
});
There's no need for temaplateObj.
If you want to assign it to an object first, use this:
var templateObj = {
name : obj.name,
from : common.tokenInfo.name,
appName : 'GAIPP',
company : company,
logo : logo,
url : url
};
res.render('modules/users/server/templates/getdeals', templateObj);

Chrome Extension context menu, differentiate image and link event

In my chrome extension I'm adding two context items "Get link" and "Get Image". The main difference being when setting them both up they have the "context" of link and image respectively. But when right clicking on an image that is acting as a link you get the option of both:
when either of those are clicked the data that comes into the listener seems to be identical, I need to be able to differentiate the two to know if the context is that of an image or a link to handle them differently. Here is my code:
chrome.runtime.onInstalled.addListener(function() {
var context = "image";
var title = "Copy Image";
var id = chrome.contextMenus.create({"title": title, "contexts":[context],
"id": "context" + context});
});
chrome.runtime.onInstalled.addListener(function() {
var context = "link";
var title = "Copy link";
var id = chrome.contextMenus.create({"title": title, "contexts":[context],
"id": "context" + context});
});
chrome.contextMenus.onClicked.addListener(onClickHandler);
function onClickHandler(info, tab) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id, {action: "imageAdded", subject: info.srcUrl}, function(response) {
});
If you want know which menu item was clicked, you can get the id value of the clicked context menu item in the menuItemId property of the object passed into the onClicked handler:
function onClickHandler(info, tab) {
console.log(info.menuItemId);
//...
}
Take a look at Parameter of onClicked callback, you could differentiate the image/link via mediaType
One of 'image', 'video', or 'audio' if the context menu was activated on one of these types of elements.

How to filter urls with # (hash tag) using UrlFilter in a chrome.declarativeContent.PageStateMatcher

I've just started building a chrome extension and as I need to display its icon only for specific urls, I used page_action.
I also used an event listening if the url changes and matches my pattern that way to display the icon:
chrome.declarativeContent.onPageChanged.addRules([
{
conditions: [
new chrome.declarativeContent.PageStateMatcher({
pageUrl: { urlContains: 'https://mysite.com/mypage.html' }
})
],
actions: [ new chrome.declarativeContent.ShowPageAction() ]
}
]);
It works fine but when I want to add a filter of the first character of the query, it fails.
The url pattern I want to filter looks like:
https://mysite.com/mypage.html#e123456789
I tried the following but it didn't help:
pageUrl: { urlContains: 'https://mysite.com/mypage.html#e' }
pageUrl: { urlContains: 'https://mysite.com/mypage.html', queryPrefix: '#e' }
pageUrl: { urlContains: 'https://mysite.com/mypage.html', queryPrefix: 'e' }
I think that the issue comes from the hash tag.
Any idea of a workaround ?
The #... part of a URL is called a "reference fragment" (ocassionally referred to as "hash").
Reference fragments are currently not supported in URLFilters, there is already a bug report for this feature: Issue 84024: targetUrlPatterns and URL search/hash component.
If you really want to show the page action depending on the state of the reference fragment, then you could use the chrome.webNavigation.onReferenceFragmentUpdated event instead of the declarativeContent API. For example (adapted from my answer to How to show Chrome Extension on certain domains?; see that answer for the manifest.json to use for testing):
function onWebNav(details) {
var refIndex = details.url.indexOf('#');
var ref = refIndex >= 0 ? details.url.slice(refIndex+1) : '';
if (ref.indexOf('e') == 0) { // Starts with e? show page action
chrome.pageAction.show(details.tabId);
} else {
chrome.pageAction.hide(details.tabId);
}
}
// Base filter
var filter = {
url: [{
hostEquals: 'example.com'
}]
};
chrome.webNavigation.onCommitted.addListener(onWebNav, filter);
chrome.webNavigation.onHistoryStateUpdated.addListener(onWebNav, filter);
chrome.webNavigation.onReferenceFragmentUpdated.addListener(onWebNav, filter);

Getting url for an attachment

I'm using CouchApp to build an easy web application that allows to upload and manage pictures. The actual image file is stored as attachment to the doc like show below.
{
"_id":"09fe82d75a26f9aa5e722d6b220180d2",
"_rev":"2-5797b822c83b9d41545139caa592f611",
"data":"some additional fields with info about the image",
"_attachments":
{
"foo.jpg":
{
"stub":true,
"content_type":"image/jpeg",
"length":23721
}
}
}
But for integrating the image in html i need the url to the attachment. How do i get this url?
I'm using evently and mustache for generating the web pages. Below is the data.js for reading the data:
function(data) {
return {
items : data.rows.map(function(r) {
return {
id : r.value._id,
rev : r.value._rev,
title : r.value.description,
url : "how am i supposed to do this?"
};
})
};
};
The URL to the attachment would be http://domain/database/09fe82d75a26f9aa5e722d6b220180d2/foo.jpg
If your filenames are dynamic, you would have to iterate the _attachments object and fetch the keys on your way - that's where your filename would be.
for(var filename in r.value._attachments){break;}
// ...
url : '<database>/' + r.value._id +'/'+filename;

Resources