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
Related
I am trying to create chrome extension that will scrap data from my webpage and then will display it in browser action window. I wanted to use background page for this, cause if i understand extensions correctly, it is only element capable of non-stop working, without need of visible tab.
The problem is, the script i wrote for background.js doesn't work properly, when i use background.js:
var location = window.location.href = 'http://localhost/index.php';
console.log(location);
manifest.json:
"background": {
"scripts": ["src/background/background.js"]
},
The answer i get is chrome-extension://some_random_text/_generated_background_page.html.
It is possible to use background pages to navigate to my webpage, then fill some forms and scrap data for later use?
This is an old question, but I recently wanted to do exactly the same.
So I'll provide an answer for others who are interested.
Setting window.location still does not work in Chrome52.
There is a workaround though. You can first fetch the web page with fetch(), and then use document.write to set the content.
This works fine, and you can then query the document and do everything you want with it.
Here is an example. (Note that I'm using the fetch API, arrow functions and LET, which all work fine now in Chrome52).
fetch("http://cnn.com").then((resp) => {
return resp.text();
}).then((html) => {
document.open("text/html");
document.write(html);
document.close();
// IMPORTANT: need to use setTimeout because chrome takes a little
// while to update the document.
setTimeout(function() {
let allLinks = document.querySelectorAll('a');
// Do something with the links.
}, 250);
});
A chrome extension has two main parts, the extension process and the browser itself. The Background Page works on the extension process. It does not have direct access and information about your webpages.
To have scripts working non-stop on your webpages, you will need to use Content Scripts.
You can then communicate between your Content Script and your Background Page using messages
contentScript.js
var location = window.location.href = 'http://localhost/index.php';
chrome.runtime.sendMessage({location: location}, function(response) {});
background.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(request.location);
});
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
I've start with phantom.js (btw I'm in love). I'm trying to make the headless browser go to my php admin panel, log in with a username and password, and from the page that it redirects to after log in i want to get some text from a div tag.
So far I manage to successfully fill the fields, create a click event, and even find the access to the DOM part of the div tag and get the inner.Text.
The only missing part for me is what to do when phantom.js clicks on a button (the log in button in this case) which will log me in and change the page content. I can't find how to handle after .click(); event.
This is the code I made so far (by the way its a good way to start with...)
var page = new WebPage();
page.open("the url comes here",
function(status){
if(status != "success"){console.log('fail loading the page');}
page.evaluate(function(){
var arr = document.getElementsByName("formname");
arr[0].elements["username"].value="username here";
arr[0].elements["password"].value="password here";
arr[0].elements["submit"].click();
return;
}
phantom.exit()
});
The code i want run on the page that comes after it is
console.log(window.frames[1].document.getElementById('status').innerHTML)
So the only question remaining is how to handle the redirect and launch the script on the other page.
Thanks,
You need to setup a new callback for the page load:
page.onLoadFinished = function(status){
console.log(window.frames[1].document.getElementById('status').innerHTML)
}
this should come right before triggering .click().
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;
});
i develop some extension for google grome
i inject at document_end event my js (+jquery)
i set in manifest allFrames: true
my match url has frameset
my goal get element by id inside one of frame
i do
//wait for load my frame
$("frame[name='header']).load(function() {
//here I need get element by id inside this frame
});
how to do this properly?
PS: my frame is from the same domain
You dont need to do document load, I assume your doing this from a content script. Just place the "run_at" manifest to be document_end and within your content script you check if the current URL is that frame page, then you will be in that Domain.
Something like this:
if(location.href == 'http://someweb.com/path/to/page.html') {
var foo = document.getElementById('foo')
Something like that will get you started.