Issues with Content Menu and Opening Tabs - Chrome Extension - javascript

im having issue with the below code not showing up with selection is detected on the webpage.
Currently when i am selecting text the context menu is not showing up.
Code
function getword(info,tab) {
if (info.menuItemId == "google") {
console.log("Google" + info.selectionText + " was clicked.");
chrome.tabs.create({
url: "http://www.google.com/search?q=" + info.selectionText,
})
} else {
console.log("Bing" + info.selectionText + " was clicked.");
chrome.tabs.create({
url: "http://www.bing.com/search?q=" + info.selectionText,
})
}
};
chrome.contextMenus.onClicked.addListener(getword);
chrome.runtime.onInstalled.addListener(function() {
var contexts = ["page","selection","link","editable"];
for (var i = 0; i < contexts.length; i++) {
var context = contexts[i];
var title = "Google Search";
var id = chrome.contextMenus.create({"title": title, "contexts":[context],
"id": "google"});
console.log("'" + context + "' item:" + id);
}
chrome.contextMenus.create({"title": "Bing Search", "id": "child1"});
});

The value of the "id" property needs to be unique. You will see the following error if you view the console of your background page:
contextMenus.create: Cannot create item with duplicate id google
at chrome-extension://ghbcieomgcdedebllbpimfgakljlleeb/background.js:23:34
Do not call chrome.contextMenus.create for each context, but assign the list of contexts to the contexts key:
chrome.runtime.onInstalled.addListener(function() {
var contexts = ["page","selection","link","editable"];
var title = "Google Search";
chrome.contextMenus.create({
"title": title,
"contexts": contexts,
"id": "google"
});
// ...
});

Related

My code has a simple issue that i cant figure out

I am setting up a link for my web page to take me to another site.
Ive tried everything i know how to do . my knowledge is limited though. basically when you visit https://beatsbycayde.com/roster/ it should take you to
"https://braytech.org/2/{destinyId}/{characterId}/legend"
for some reason it doesnt And I cannot figure out why any help would be greatly appreciated it it instead takes you to
https://braytech.org/2/{destinyId}/fstats/legend
I know that i have fstats in there iam trying to us it as an object and call it in the href
// get list of members and populate roster table
var roster = [];
$.when($.ajax({
url: "https://www.bungie.net/platform/GroupV2/699392/Members/",
headers: {
"X-API-Key": "47b810e692d64237911c2cbe0d433cfe"
}
}).success(function(json) {
if (json.ErrorStatus === 'Success') {
roster = json.Response.results;
console.log('Exalted member list:', roster);
} else {
alert('Uh oh, looks like Bungie\'s doing server maintenance or having problems. Please check back again soon!');
console.log(json);
}
}).error(function(json) {
alert('Uh oh, looks like Bungie\'s doing server maintenance or having problems. Please check back again soon!');
console.log(json);
}), $.ajax({
url: 'https://www.bungie.net/platform/destiny2/2/profile/4611686018429000034/?components=200',
headers: {
'X-API-Key': "47b810e692d64237911c2cbe0d433cfe"
}
}).success(function(res) {
console.log('PS4 stats:', res);
})).then(function() {
listMembers(roster);
});
function listMembers(rsp) {
var list = $('.memberList-list'),
on = 0,
sortMembers = function(method) {
// sort by date joined
if (method = joined) {
list.find('.member').sort(function(a, b) {
return ($(b).data('joined')) < ($(a).data('joined')) ? 1 : -1;
}).appendTo(list);
} else if (method = username) {
list.find('.member').sort(function(a, b) {
return ($(b).data('username')) < ($(a).data('username')) ? 1 : -1;
}).appendTo(list);
}
list.find('.member.online').prependTo(list);
};
for (var i = 0; i < rsp.length; i++) {
var profile = rsp[i].bungieNetUserInfo,
member = $('<a></a>');
// tally up online members
if (rsp[i].isOnline) {
on++
}
// check for valid profile
// some users don't have Bungie profiles somehow and it breaks function
if (typeof profile != 'undefined') {
// store response data in semantic variables
var name = rsp[i].destinyUserInfo.displayName,
joinDate = rsp[i].joinDate,
joined = joinDate.substring(0, joinDate.indexOf('T')),
online = rsp[i].isOnline,
icon = profile.iconPath,
memberId = profile.membershipId,
memberType = rsp[i].destinyUserInfo.membershipType,
destinyId = rsp[i].destinyUserInfo.membershipId,
rank = rsp[i].memberType;
// configure D OM node and add to page
$('#destiny-Id').text(destinyId);
$.ajax({
url: "https://www.bungie.net/Platform/Destiny/2/Account/" + destinyId + "/",
headers: {
"X-API-Key": "47b810e692d64237911c2cbe0d433cfe"
}
}).done(function(json) {});
$(function() {
$.ajax({
url: "https://www.bungie.net/Platform/Destiny/2/Account/4611686018429000034/",
headers: {
"X-API-Key": "47b810e692d64237911c2cbe0d433cfe"
},
success: function(data) {
// Gambit stats
var fstats = data.Response.data.characters[0].characterBase.characterId;
// Populate stats
// pvp
$('#player-f-stats').text(fstats);
},
error: function(data) {
alert('Uh oh, failed to load player stats! Looks like Bungie\'s doing server maintenance or having problems. Please check back again soon!');
console.log('Error loading player stats:', data);
}
});
});
member.attr({
'class': 'j-row vertical-center-row member',
'href': '/player/?bungieId=' + memberId + '&destinyId=' + destinyId + '&joined=' + joined + '&rank=' + rank,
'title': 'See player profile for ' + name,
'data-joined': joined.replace(/-/g, ''),
'data-username': name,
'data-online': 'false',
'data-searchable': name,
}).html('<div class="j-col j-col-1 member-icon"><img src="https://bungie.net/' + icon + '"></div>' + '<div class="j-col j-col-3 member-name"><h3>' + name + '</h3></div>' + '<div class="j-col j-col-3 member-joined" data-label="Joined">' + joined.replace(/-/g, '/') + '</div>' + '<div class="j-col j-col-3 member-status" data-label="Status"><span class="member-online" id="status-' + memberId + '">' + online + '</span></div>' + '<div class="j-col j-col-3 member-button"><a class="button outline gold full-width">' + 'View Stats' + '</a></div>' + '<div class="j-col j-col-3 member-button"> + In Depth Stats' + '</a></div>').appendTo(list);
// indicate online/offline status
if (String(online) === 'true') {
$('#status-' + memberId).text('Online').addClass('online').closest('.member').attr('data-online', true).addClass('online');
} else {
$('#status-' + memberId).text('Offline').removeClass('online');
}
sortMembers(joined); // sort members by join date
}
}
}
You have nested links. That breaks your HTML and prevents the href you want to be used.
Here you create the wrapper of each member. Which is a link.
member.attr({
'class': 'j-row vertical-center-row member',
'href': '/player/?bungieId=' + memberId + '&destinyId=' + destinyId + '&joined=' + joined + '&rank=' + rank,
...
And then you append another link inside of it here:
... In Depth Stats' ...
So I would suggest that you change the structure of your member element. Maybe place the top link in the position of the View Stats button and change that button to a <a> tag. But then as a consensus the whole member element won't be clickable, only the links.
Good luck!

Check if file exists by checking two different naming conventions using jQuery/JS

I am trying to to build out profile pages for multiple users which include personalized photos/items that are stored are on a server. These items are labeled/named using the users' name. A user has a FirstName & LastName, with the option of using a PreferredName.
Initially, the items were named using PreferredName over Firstname if a Preferred Name existed. (ex: Fname: Robert; Lname: Smith; Pname: Bobby; FileName = SmithBobby.file)
Unfortunately, the user now has the ability to change their name on their profile from PreferredName back to FirstName, leading to a large portion of profiles to look for the incorrect file (item is actually named SmithBobby.file, while the profile is looking for SmithRobert.file.)
This being said, I would like to check for the item using both naming conventions (FirstLast.file & PreferredLast.file), if neither exists, it should default to use the default/generic photo. (default.file)
The below example is how I currently check to see if the user has a CV and profile picture on file. If no CV exists, it removes the element from the page. if the image doesn't exist, it defaults to default.jpg.
if (($.PageData.PreferredName == "") || ($.PageData.PreferredName == null)) {
$("#Name").text($.PageData.FirstName + " " + $.PageData.LastName);
document.title = ($.PageData.FirstName + " " + $.PageData.LastName + " | Profile");
$("#BioPageTitle").text($.PageData.FirstName + " " + $.PageData.LastName);
} else {
$("#Name").text($.PageData.PreferredName + " " + $.PageData.LastName);
document.title = ($.PageData.PreferredName + " " + $.PageData.LastName + " | Profile");
$("#BioPageTitle").text($.PageData.PreferredName + " " + $.PageData.LastName);
}
//FILENAME BUILD
var file_name = ($.PageData.LastName + $.PageData.FirstName);
var second_fname = ($.PageData.LastName + $.PageData.PreferredName);
file_name = file_name.replace(/[^0-9a-z]/gi, '');
second_fname = second_fname.replace(/[^0-9a-z]/gi, '');
var vita = $('#Vita');
var vita_url = "vita/" + file_name + ".pdf";
var second_vitaURL = "vita/" + second_fname + ".pdf";
var VitaLink = $("<a>").attr({
href: vita_url,
target: '_blank'
}).html("<strong>Curriculum Vitae</strong>");
$.get(vita_url)
.done(function() {
vita.html(VitaLink);
}).fail(function() {
vita.remove();
});
/*PHOTO BUILD/CHECK */
//PROFILE PICTURE
var img = $('#ProfilePicture');
var default_url = "photos/default.jpg";
var img_url = "photos/" + file_name + ".jpg";
img.error(function() {
$(this).attr('src', default_url);
});
img.attr('src', img_url);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You should be able to extend your current function that checks the first link by checking for the second one if the first one fails. If the second one fails too, then you can remove the entry.
$.get(vita_url)
.done(function() {
vita.html(VitaLink);
}).fail(function() {
$.get(second_vitaURL)
.done(function() {
//modify the VitaLink with the correct url, if this doesn't work make a separate vitaLink type variable
VitaLink.attr('href', second_vitaURL);
vita.html(VitaLink);
}).fail(function() {
vita.remove();
});
});

zimlet change url if it is a file link than correct link or start external program

I have a problem in browser with sent file links:
file:/// instead of file:// and i would like to create a zimlet which is check links in mail and if it is a file link then change file:/// to file:// and start on click.
Or start external program if it is a file link. I created the link reader program but i don't know how to start it or implement to a zimlet.
Do you have any idea?
thanks in advance for any help.
My example for link correction in .net but how it looks like in java ajax:
foreach (string b in args)
{
// Console.WriteLine(b);
if (b.Contains("file:F"))
{
string d = b.Replace(#"file:F", #"F");
System.Diagnostics.Process.Start(d);
}
else if (b.Contains("file:///F:"))
{
string d = b.Replace(#"file:///F:", #"F:");
System.Diagnostics.Process.Start(d);
}
}
Here the string is readed and checked and replaced with good starting chars.
I think it have to work in java too but i am not good in java.
Please Help!
I tried with converter: But it not works:
try
{
for (String b : args)
{
// Console.WriteLine(b);
if (b.contains("file:F"))
{
String d = b.replace("file:F", "F");
System.Diagnostics.Process.Start(d);
}
else if (b.contains("file:///F:"))
{
String d = b.replace("file:///F:", "F:");
System.Diagnostics.Process.Start(d);
}
else
{
System.out.println("File Not Contain Valid File Link!");
System.out.println("Or File Missing!");
Console.ReadKey();
}
// Console.WriteLine(d);
// Console.ReadKey();
// System.Diagnostics.Process.Start(d);
}
}
catch (RuntimeException e)
{
System.out.println("File Not Contain Valid File Link!");
System.out.println("Or File Missing!");
Console.ReadKey();
}
I have a new idea!
How can i run links automatically in new tab?
Like if i click on a link than automatically open new tab and copy url to there and run. It have to be an right-click menu i think. It should work.
UPDATE:
Now i using an example: for right click menu now it is working on click pop up message:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// The onClicked callback function.
function onClickHandler(info, tab) {
if (info.menuItemId == "radio1" || info.menuItemId == "radio2") {
console.log("radio item " + info.menuItemId +
" was clicked (previous checked state was " +
info.wasChecked + ")");
} else if (info.menuItemId == "checkbox1" || info.menuItemId == "checkbox2") {
console.log(JSON.stringify(info));
console.log("checkbox item " + info.menuItemId +
" was clicked, state is now: " + info.checked +
" (previous state was " + info.wasChecked + ")");
} else {
console.log("item " + info.menuItemId + " was clicked");
console.log("info: " + JSON.stringify(info));
console.log("tab: " + JSON.stringify(tab));
}
Pop-up message is here
alert("I am an alert box!");
};
chrome.contextMenus.onClicked.addListener(onClickHandler);
// Set up context menu tree at install time.
chrome.runtime.onInstalled.addListener(function() {
// Create one test item for each context type.
var contexts = ["page","selection","link","editable","image","video",
"audio"];
for (var i = 0; i < contexts.length; i++) {
var context = contexts[i];
var title = "Test '" + context + "' menu item";
var id = chrome.contextMenus.create({"title": title, "contexts":[context],
"id": "context" + context});
console.log("'" + context + "' item:" + id);
}
// Create a parent item and two children.
chrome.contextMenus.create({"title": "Test parent item", "id": "parent"});
chrome.contextMenus.create(
{"title": "Child 1", "parentId": "parent", "id": "child1"});
chrome.contextMenus.create(
{"title": "Child 2", "parentId": "parent", "id": "child2"});
console.log("parent child1 child2");
// Create some radio items.
chrome.contextMenus.create({"title": "Radio 1", "type": "radio",
"id": "radio1"});
chrome.contextMenus.create({"title": "Radio 2", "type": "radio",
"id": "radio2"});
console.log("radio1 radio2");
// Create some checkbox items.
chrome.contextMenus.create(
{"title": "Checkbox1", "type": "checkbox", "id": "checkbox1"});
chrome.contextMenus.create(
{"title": "Checkbox2", "type": "checkbox", "id": "checkbox2"});
console.log("checkbox1 checkbox2");
// Intentionally create an invalid item, to show off error checking in the
// create callback.
console.log("About to try creating an invalid item - an error about " +
"duplicate item child1 should show up");
chrome.contextMenus.create({"title": "Oops", "id": "child1"}, function() {
if (chrome.extension.lastError) {
console.log("Got expected error: " + chrome.extension.lastError.message);
}
});
});
And i created a hta file which is running my exe:
<script type="text/javascript" language="javascript">
var oShell = new ActiveXObject("Shell.Application");
var commandtoRun = "F:\\ABLAGE\\link_reader_ip.exe";
oShell.ShellExecute(commandtoRun,"","","open","1");
</script>
New problems:
1. How to start on click hta file:
function callShellApplication(){
var objShell = new ActiveXObject("WScript.shell");
objShell.Run('"d:\\test.hta"');
}
no error , but the test.hta file wont start.
if the hta run my file it opens an extra window but i wont.
Please someone help me.

child links in quick launch navigation in sharepoint

https://msdn.microsoft.com/en-us/library/office/jj247080.aspx
based on example on this site for getting quick lunch url and quick lunch title
we have something like this
while (nodeEnumerator.moveNext()) {
var node = nodeEnumerator.get_current();
nodeInfo += '{"title":"' + node.get_title() + '",' + '"link":"' + node.get_url() + '"},';
}
but if any of those navigation urls have any childs I don't know how to get that
so how to get that?
Use SP.NavigationNode.children property to get the collection of child nodes of the navigation node.
Note: SP.NavigationNode.children property needs to be requested
explicitly in query, this is why in the below example it is specified via Include expression:
ctx.load(quickLaunchNodes,'Include(Title,Url,Children)');
Example
var ctx = SP.ClientContext.get_current();
var web = ctx.get_web();
var quickLaunchNodes = web.get_navigation().get_quickLaunch();
ctx.load(quickLaunchNodes,'Include(Title,Url,Children)');
ctx.executeQueryAsync(function() {
printNodesInfo(quickLaunchNodes);
},
function(sender, args) {
console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
});
function printNodesInfo(nodes){
nodes.get_data().forEach(function(node){
var childNodes = node.get_children();
console.log(String.format('{0} child nodes:',node.get_title()));
childNodes.get_data().forEach(function(childNode){
console.log(String.format('Title: {0} Url: {1}',childNode.get_title(),childNode.get_url()));
});
});
}

Why is Chrome ignoring my executeScript command in my extension?

I'm trying to figure out exactly how Content Scripts work.
I'm writing an extension with a context menu that, once the option is clicked, the next click will result in an alert dialog with information about the page the element is on and the id and name of the element clicked.
I think my problem is including the name of the content script file somewhere on my manifest, since I am using executeScript to use it instead of having it injected on every single web page but I cannot figure out where to put it.
Please let me know if I can provide more helpful information.
Here are copies of my manifest, the main script I use and the script that I am trying to insert.
Manifest.json
{
"name": "Omnixx Page Object Builder",
"description": "Finds information about an element clicked, started with a context menu",
"version": "0.3",
"permissions": ["tabs", "contextMenus", "activeTab"],
"background": {
"persistent": false,
"scripts": ["menuBuilder.js"]
},
"manifest_version": 2
}
menuBuilder.js
function onClickHandler(info, tab) {
if (info.menuItemId == "start") {
console.log("Started trying to find elements");
chrome.tabs.executeScript(null, {file:"elementTracker.js"});
console.log("Started listening...");
}
};
chrome.contextMenus.onClicked.addListener(onClickHandler);
chrome.runtime.onInstalled.addListener(function() {
chrome.contextMenus.create({"title": "Find element information", "id": "start", "contexts":["all", "page", "frame", "selection", "link", "editable", "image","video", "audio"], });
});
elementTracker.js
function click(event) {
// Begin building the message
var msgToWrite = "";
var curscreen = window.HIDEFRAME.document.getElementsByName("curscreen")[1].value;
msgToWrite += "curscreen: '" + curscreen + "'\n";
var url = content.document.URL;
msgToWrite += "URL: " + url + "\n";
// A try-catch block is necessary for finding the frame; otherwise the code
// will fail for pages without frames
try {
var frame = event.originalTarget.ownerDocument.defaultView.frameElement;
var frameName = frame.getAttribute("name");
if (frameName != null) {
msgToWrite += "Frame: '" + frameName + "'\n";
} else {
msgToWrite += "No frame found\n";
}
} catch (e) {
msgToWrite += "No frame found\n";
}
// Get the element's ID
var elemID = event.target.getAttribute("id");
if (elemID != null) {
msgToWrite += "ID: '" + elemID + "'\n";
} else {
msgToWrite += "No ID found\n";
}
// Get the element's name
var elemName = event.target.getAttribute("name");
if (elemName != null) {
msgToWrite += "Name: '" + elemName + "'";
} else {
msgToWrite += "No name found";
}
// Create a pop-up message
alert(msgToWrite);
}
document.addEventListener('click', click);
What I think is happening is that you're trying to call another event listener at the end of your elementTracker.js file. You don't need that because you're initializing the script from the context menu call.
Change the last line in that script to click(event). The script will be injected to the page from the context menu.

Categories

Resources