New to Chrome programming, but am more or less familiar with Javascript.
Goal:
A Chrome add-on that will allow me to:
1) Right-click on an link
2) then add a some more characters to that link
3) then reload the page with the new constructed URL.
EX:
A. Object has a link : www.address.com/34922
B. User righ-clicks on that object (Chrome's menu appears [which I know how to mod]), a menu option appears 'reconstruct rul.'
C. The add-on adds '/subfolderA' to the above mentioned url.
D. Page reloads with the following URL: www.address.com/34922/subfolderA
Thanks,
Steve
Use the chrome.contextMenus API, more specifically the create method.
// Add this to the background page
chrome.contextMenus.create({
title: 'Open this link plus /subfolderA',
contexts: ['link'],
onclick: function(info, tab) {
var linkUrl = info.linkUrl;
// Some logic, eg adding a fragment:
linkUrl += '/subfolderA';
// Replace URL on current tab
chrome.tabs.update(tab.id, {url: linkUrl});
},
// The following array should consist of valid match patterns
// This context menu item will only be visible on matching links
targetUrlPatterns: ['http://adress.com/*']
});
Relevant documentation
Used methods:
chrome.contextMenus API
chrome.tabs.create(<object createProperties>)
The onClickData type. This is just a plain JavaScript object. However, Chrome will validate this object, and throw an error when an unknown format (e.g. wrong property) is used.
chrome.tabs API
chrome.tabs.update(<integer tabId>, <object updateProperties>)
Further reading:
Background pages
Manifest file
Match patterns
Related
Basically I just want to check links across different environments and thats just a different domain name. So basically I have my extension so far with buttons for each one but am having trouble getting anything to happen. Tried in b ackground.js as I thought that was the only place to access tab?
Tried this and some other variations but yeah this is very new to me so forgive my ignorance. I know javascript well enough but this is taking a bit to adjust.
let dev = document.getElementByID("dev");
console.log(dev);
dev.onclick = function(element) {
chrome.tabs.query({currentWindow: true, active: true}, function (tab) {
chrome.tabs.update(tab.id, {url: "www.google.com"});
});
1) An URL must start with a scheme: https://www.google.com. 2) Make sure to read about the extensions overview::architecture - the popup is a separate page with its own window, URL, and devtools which you can access by rightclicking the popup, then clicking Inspect. 3) Hint: no need to use tabs.query to change the active tab - simply omit tab.id, from tabs.update as it's an optional parameter. – wOxxOm
Thanks that helped a lot!
I have a perhaps simple question. What would be the difference between an <a> tag and a normal GET request with any element. I know the <a> tag automatically sends you to the url specified in its href attribute. So I assume that a Get request does something similar in it's success callback (as demonstrated below)
But let's say that I also want to send some information along with a normal get request when a for example <span> element is clicked on so I write:
$('span').click(() => {
$.ajax({
url: '/someurl',
type: 'GET',
data: {
title: someTitle,
email: someEmail
},
success: (data) => {
window.location = '/someurl';
}
});
});
Is there any way to achieve this with an <a> tag? Sending information to the server so it's available in req.query.title and req.query.email ?
Doing the ajax request above will run my app.get('/someurl',(req,res)=>{})twice because I am sending a GET request to send the data (title and email) and then I am making another GET request when I write window.location = '/someurl' How can I redo this so that it only sends the GET request ONCE but also allows for the sending and storing information to the req object AND ensures that the browser is now displaying /someurl.
Just create the appropriate query string in the URL you put in the href of the <a> tag and it will work just like your ajax call. Suppose someTitle has the value of "The Hobbit" and someEmail has the value of foo#whatever.com, then you can construct that URL like this:
Click Me
A number of non-letter characters have to be escaped in URLs. In the above URL, the space is replaced with %20 and the # with %40. In your particular example, you could open the network tab in the chrome debugger and see the EXACT URL that Chrome was sending for your ajax call, copy that to the clipboard and insert it into your <a> tag.
Here's a table that shows what characters have to be replaced in a query string component (the part after & or after =):
I'm just wondering then, aside from semantic reasons, is there any other advantages to using an a tag instead of anything else?
<a> tags are understood by all sorts of machines that may read your page such as screen readers for the disabled or crawlers indexing your site. In addition, they work automatically with browser keyboard support, Ctrl-click to open a new tab. Whereas a piece of Javascript may not automatically support any of that functionality. So, basically, if the <a> tag can do what you need it is widely preferred because it has so much other default functionality that can be necessary or handy for users.
Hello
I'm brand new to making Chrome Extensions and have done the simple tutorials, but I'm having trouble finding what I need. I want the extension to allow a user to chose an image on a webpage, and then copy the URL for that image into the extension. Can anyone help me out? I'm sure if I see an example I'd get a better grasp on how extensions can interact with a page.
From what I understand of your question, I'd say you want to create a context menu item that shows up when you right-click an image. For example, in your background script, use:
chrome.contextMenus.create({
title: "Use URL of image somehow",
contexts:["image"],
onclick: function(info) {
handleImageURL(info.srcUrl);
}
});
function handleImageURL(url) {
// now do something with the URL string in the background page
}
This will add a context menu item that shows up on all pages, but only when you right-click on images. When the user selects it, the onclick handler of the menu item fires handleImageURL with the URL of the image as the argument. The URL can be processed in any way you like, e.g., saved in a localStorage list, sent to a server via Ajax, or passed in a message to a listening content script in the current tab.
EDIT with alternative:
You might want a content script that gets injected into every page. The script could bind an event listener to every image element at load time:
// in my_content_script.js...
var imgs = document.getElementsByTagName("img");
for(var i = 0, i < imgs.length; ++i) {
imgs[i].addEventListener("click", function() {
alert(this.src);
// do things with the image URL, this.src
});
}
To inject it into all subdomains of example.com, your manifest would include:
...
"content_scripts": {
"matches":["*://*.example.com/*"],
"scripts":["my_content_script.js"]
},
...
Note that this pure-JS solution doesn't attach listeners to images dynamically added after load time. To do that in your content script with jQuery, use:
$(document).on("click", " img", function() {
alert(this.src);
});
And add your jQuery file name to the scripts array in your manifest, next to my_content_script.js.
Based on this Google Chrome Extension sample:
var images = [].slice.apply(document.getElementsByTagName('img'));
var imageURLs = images.map(function(image) {
return image.src;
});
chrome.extension.sendRequest(images);
For a more detailed example (e.g. how to handle the request), you can check out this extension I wrote called Image Downloader
Basically what I have a List that will be maintained by the user that has a field that contains a link to an RSS feed.
I tried using the OOTB RSS and it's great, but you have to specify the feed URL and I need that to be based on user selection. For example, the user will select from a list a feed they want to view and this should take them to the feed reader page which will use their selection to get the feed URL and display this on the page.
An alternative which is not a general Sharepoint solution is to use jquery.
Is the list visible on the page or is it "just" a list in Sharepoint?
Of course you might need some kind of proxy to do this in order to call the rss-feeds if they are placed on another server. But you will send the performance to the client instead of the server which is a plus..
My solution was to use the WebPartPages Web Service (SaveWebPart) to change the definition of the web part to use the new feed URL whenever a feed is clicked on.
I created a javascript function the will accept the feed URL and proceed to the page where the feed is displayed. The new feed will not be loaded until the next time you visit the page, therefore if you are already on it you will need to reload, thus the redirect.
For more information on the format of the request and the web part XML format see the following page.
http://msdn.microsoft.com/en-us/library/ms774839%28v=office.12%29.aspx
function SetFeed(feedURL){
var webPartGUID = $("#<WebPartID>").attr('webpartid');
// This is where you set the page URL, Full Web Part XML (including path to FEED),
// storageKey (webPart GUID), and storage type (none, personal, shared)
var soapEnv = "<FULL SOAP XML>";
jQuery.ajax({
url: "http://<SITE PATH>/_vti_bin/WebPartPages.asmx",
type: "POST",
dataType: "xml",
data: soapEnv,
beforeSend: function(xhr) {
xhr.setRequestHeader("SOAPAction",
"http://microsoft.com/sharepoint/webpartpages/SaveWebPart")
},
complete: function(xData, status){
window.location='REDIRECT TO FEED PAGE';
},
contentType: "text/xml;charset='utf-8'"
});
}
I'm writing a Chrome extension. As part of the extension, I want to get the URL of the tab that the extension was called from. What's the difference between using:
chrome.tabs.getSelected(null, function(tab) { var myTabUrl = tab.url; });
and
chrome.tabs.getCurrent(function(tab) { var myTabUrl = tab.url; });
?
Method chrome.tabs.getSelected has been deprecated. You should use chrome.tabs.query instead now.
You can't find the official doc for obsolete method chrome.tabs.getSelected. Here is the doc for method chrome.tabs.query.
getCurrent should be what you need, getSelected is a tab that is currently selected in a browser. When they could be different - maybe your extension runs some background cronjob in tabs, so that tab could be not currently selected by a user.
Ok I got it all wrong apparently. getCurrent should be used only inside extension's own pages that have a tab associated with them (options.html for example), you can't use it from a background or popup page. getSelected is a tab that is currently selected in a browser.
As to your original question - you probably need neither of those two. If you are sending a request from a content script to a background page, then the tab this request is being made from is passed as a sender parameter.
For those who is looking for working example of chrome.tabs.query instead of deprecated chrome.tabs.getSelected:
chrome.tabs.query({
active: true,
lastFocusedWindow: true
}, function (tabs) {
var myTabUrl = tabs[0].url;
});