I m using chrome.commands API and trying to build a extension which shows a input box popup in which I can enter search query and press enter and it will search it on google for me in new tab.
But the problem is even when I press given command i.e. Alt+5 in this case it does not show anything.
This is my first time trying to make chrome extension so maybe I#m missing something.
Below is the code:
logic.js
chrome.commands.onCommand.addListener(function(command) {
if(command == toggle){
d = document;
var f = d.createElement('form');
f.action = '';
f.method = 'get';
var i = d.createElement('input');
i.id = 'bar';
i.type = 'text';
i.name = 'search';
f.appendChild(i);
d.body.appendChild(f);
document.getElementById("bar").addEventListener('keydown',(e)=>{
var query = document.getElementById("bar").value;
var gString = "https://www.google.co.in/search?q=";
var newUrl = gString + query;
if(e.keyCode == 13){
chrome.tabs.create({url: newUrl});
}
},false);
}
});
manifesto.json
{
"manifest_version": 2,
"name" : "shortcut google",
"description": "press keys shift+g for a instant google search",
"version": "1.0",
"browser_action": {
"default_popup": "search.html"
},
"commands":
{
"toggle" :
{
"suggested_key": {
"default": "Alt+5",
"mac": "Command+Shift+5"
},
"description" : "toggle the search bar.",
"global": true
}
},
"permissions": [
"tabs"
]
}
search.html
<!DOCTYPE html>
<html>
<head>
<title>google search</title>
<script type="text/javascript" src="logic.js"></script>
</head>
<body>
</body>
</html>
Related
I am building a simple page-scraping chrome extension to get a page's title and the contents of a shopping cart. I am getting the shopping cart contents twice but not the tittle page. The chrome.runtime.onMessage.addListener() function is returning the same message twice to popup.html and getting a duplicate of the shopping cart's content and no page title. I have tried to construct the chrome.runtime.onMessage.addListener()in different ways, to no avail. Please advise on where I went wrong or suggest a better approach?
manifest.json
(permissions are allowed on all urls but I'm currently testing the extension on the checkout page of an ecommerce website)
"manifest_version": 2,
"name": "Webscraper Extension",
"description": "Webscraper extension for Chrome",
"version": "1.0",
"background": {
"scripts": ["popup.js"],
"persistent": true
},
"permissions": [
"tabs",
"http://*/",
"https://*/"
],
"browser_action": {
"default_icon": "logo.png",
"default_popup": "popup.html"
}
poppup.html
<!doctype html>
<html>
<head>
<title>Webscraping Extension</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h3>Checkout</h1>
<p id='pagetitle'>This should change to the scraped title!</p>
<div id='cart'>Cart here!</div>
<button id="checkout" class "button">Checkout</button>
</body>
<script src="popup.js"></script>
</html>
popup.js
// Inject the payload.js script into the current tab after the popout has loaded
window.addEventListener('load', function (evt) {
chrome.extension.getBackgroundPage().chrome.tabs.executeScript(null, {
file: 'payload.js'
});;
});
// Listen to messages from the payload.js script and write to popout.html
chrome.runtime.onMessage.addListener(function (message) {
document.getElementById('pagetitle').textContent = message;
document.getElementById('cart').textContent = message;
});
payload.js
// send the page title as a chrome message
chrome.runtime.sendMessage(document.title);
//send the cart as chrome message
var result = "";
var cartitems = document.getElementsByClassName("item-list");
for (var i = 0; i < cartItems.length; i++) {
result += cartItems[i].textContent;
}
chrome.runtime.sendMessage(result);
You have only one message listener that overwrites the textContent of both pagetitle and cart with whatever message it receives. Therefore, both are overwritten with result, which is the latest message received.
Try discriminating the messages with something like:
popup.js
chrome.runtime.onMessage.addListener(function (message) {
if (message.title) document.getElementById('pagetitle').textContent = message.title;
if (message.cart) document.getElementById('cart').textContent = message.cart;
});
payload.js
// send the page title as a chrome message
chrome.runtime.sendMessage({title:document.title});
//send the cart as chrome message
var result = "";
var cartitems = document.getElementsByClassName("item-list");
for (var i = 0; i < cartItems.length; i++) {
result += cartItems[i].textContent;
}
chrome.runtime.sendMessage({cart:result});
I have created chrome extension. I want to open current page URL when click on chrome icon. Now show current page URL in popup. Please help me what can I do in this case.
Please find below code:
document.addEventListener('DOMContentLoaded', function() {
var checkPageButton = document.getElementById('checkPage');
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
var url = tabs[0].url;
alert(url);
});
checkPageButton.addEventListener('click', function() {
chrome.tabs.getSelected(null, function(tab) {
d = document;
var f = d.createElement('form');
f.action = 'http://gtmetrix.com/analyze.html?bm';
f.method = 'post';
f.target = '_blank';
var i = d.createElement('input');
i.type = 'hidden';
i.name = 'url';
i.value = tab.url;
f.appendChild(i);
d.body.appendChild(f);
f.submit();
});
}, false);
}, false);
<!-- Menifest.json -->
{
"manifest_version": 2,
"name": "Test ",
"description": "",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"activeTab"
]
}
<!-- popup.html -- >
<html>
<head>
<title>GTmetrix Analyzer</title>
<script src="popup.js"></script>
</head>
<body>
<h1>GTmetrix Analyzer</h1>
<button id="checkPage">Check this page now!</button>
</body>
</html>
Can anyone please help me to sort-out this issue?
Thanks
Based on our discussion in comments. Posting this as an answer.
If you want to grab the url of current tab and open it in a new window. Do following changes in your popup js file
Replace this code:
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
var url = tabs[0].url;
alert(url);
});
With this code:
chrome.tabs.query({'active': true, currentWindow: true}, function (tabs) {
var url = tabs[0].url;
chrome.tabs.create({url: url}, function(tab){});
});
This will grab the current tab url and open it in a new a new tab.
Also, you can get rid of this code, it is not required anymore.
checkPageButton.addEventListener('click', function() {
chrome.tabs.getSelected(null, function(tab) {
d = document;
var f = d.createElement('form');
f.action = 'http://gtmetrix.com/analyze.html?bm';
f.method = 'post';
f.target = '_blank';
var i = d.createElement('input');
i.type = 'hidden';
i.name = 'url';
i.value = tab.url;
f.appendChild(i);
d.body.appendChild(f);
f.submit();
});
}, false);
I am new to chrome extension development and stuck at one point. Please help me.
Purpose of extension: This extension simple wants google login.
Work done so far:
index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/creative.css" type="text/css">
<title>TrustWall Authentication</title>
<script src="index.js"></script>
</head>
<body>
<header>
<div class="header-content">
<div class="header-content-inner">
<div id="title">
<h1 id="s">TrustWall Demo</h1>
</div>
<hr>
<p>This is a demo Plugin demostrating Trustwall touchID based
login</p>
<div id="google_login">
<input id="google" type="button" value="Login by google"
class="btn btn-primary btn-xl page-scroll" />
</div>
<div id="sclconnect_login">
<input id="sclconnect" type="button" value="Login using TrustWall"
class="btn btn-primary btn-xl page-scroll" />
</div>
</div>
</div>
</header>
<div id="profile"></div>
</body>
</html>
manifest.json
{
"manifest_version": 2,
"name": "Getting started example",
"description": "This extension shows a Google Image search result for the current page",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "index.html"
},
"permissions": [
"activeTab",
"https://www.googleapis.com",
"http://*.google.com/"
],
"content_security_policy": "script-src 'self' https://apis.google.com; object-src 'self'"
}
index.js
function init(){
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/client.js?onload=onLoadCallback';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
}
function logout()
{
gapi.auth.signOut();
location.reload();
}
function login()
{
var myParams = {
'clientid' : '775263086375-33h1eij26jocplkkv52h08jlfifohvkp.apps.googleusercontent.com',
'cookiepolicy' : 'single_host_origin',
'callback' : 'loginCallback',
'approvalprompt':'force',
'scope' : 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.profile.emails.read'
};
gapi.auth.signIn(myParams);
}
function loginCallback(result)
{
if(result['status']['signed_in'])
{
var request = gapi.client.plus.people.get(
{
'userId': 'me'
});
request.execute(function (resp)
{
var email = '';
if(resp['emails'])
{
for(i = 0; i < resp['emails'].length; i++)
{
if(resp['emails'][i]['type'] == 'account')
{
email = resp['emails'][i]['value'];
}
}
}
var str = "Name:" + resp['displayName'] + "<br>";
str += "Image:" + resp['image']['url'] + "<br>";
str += "<img src='" + resp['image']['url'] + "' /><br>";
str += "URL:" + resp['url'] + "<br>";
str += "Email:" + email + "<br>";
document.getElementById("profile").innerHTML = str;
var e = document.getElementById("google_login");
e.style.display = "none";
var e1 = document.getElementById("sclconnect_login");
e1.style.display = "block";
});
}
}
function onLoadCallback()
{
gapi.client.setApiKey('AIzaSyA4o1P6gHvaX1aem0lLNvKgVCSrxtge0pg');
gapi.client.load('plus', 'v1',function(){});
document.getElementById("google").onclick = login;
}
document.addEventListener('DOMContentLoaded', function () {
init();
var sclConnectBtn = document.getElementById("sclconnect_login");
sclConnectBtn.style.display='none';
});
This plugin gives me Origin_mismatch error.
This might be because of improper javascript origin which needs to be mentioned in console. But dont know what to write there in javascript origin. My manifest.json has requested the permission for google.
I'm building a Chrome Extension with Youtube API access. But I don't get an authentification against Youtube. It looks like there is no up-to-date source or sample. The Tutorial here uses some chrome-oauth lib from 2010, the other Source here uses a different lib, I guess its useful for browser based Auth & API access.
I have a Dev Key, a client id for installed apps (type: Chrome), YT API Key (Simple API Access).
My Chrome App uses following manifest:
{
"name": "Youtube Chrome Ext",
"version": "1.0",
"manifest_version": 2,
"description": "Youtube Chrome Ext",
"app": {
"launch": {
"local_path": "main.html",
"container":"tab"
}
},
"options_page": "settings.html",
"background": {
"page": "background.html"
},
"permissions": [
"tabs",
"http://gdata.youtube.com/",
"https://www.google.com/accounts/OAuthGetRequestToken",
"https://www.google.com/accounts/OAuthAuthorizeToken",
"https://www.google.com/accounts/OAuthGetAccessToken",
"https://www.googleapis.com/auth/youtube"
]
}
with following backgroundHandler.js file for authentification with Youtube over oAuth2.0:
(function(global){
global.backgroundHandler = {
initBackground : function(){
var self = this;
var oauth = ChromeExOAuth.initBackgroundPage({
'request_url' : 'https://www.google.com/accounts/OAuthGetRequestToken',
'authorize_url' : 'https://www.google.com/accounts/OAuthAuthorizeToken',
'access_url' : 'https://www.google.com/accounts/OAuthGetAccessToken',
'consumer_key' : 'anonymous',
'consumer_secret' : 'anonymous',
'scope' : 'http://gdata.youtube.com',
'app_name' : 'YouTube Ext'
});
oauth.authorize(this.onAuthorized());
},
onAuthorized : function() {
//I'm not authorized - no window with grant access was displayed ...
}
};
})(window);
document.addEventListener('DOMContentLoaded', function () {
backgroundHandler.initBackground();
});
Note Youtube don't uses consumer key & secret.
background.html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/oAuth/chrome_ex_oauthsimple.js"></script>
<script type="text/javascript" src="js/oAuth/chrome_ex_oauth.js"></script>
<script type="text/javascript" src="js/handler/backgroundHandler.js"></script>
</head>
<body>
</body>
</html>
My biggest problem is to get somehow the OAuth done and do authentificated requests against Youtube. It looks like for me, that there exists no source on the whole www which is up-to-date.
I would be glad if someone could help me.
BR,
mybecks
I did a little experiment and I tested this library:
https://github.com/borismus/oauth2-extensions
I followed the steps indicated by the author and I changed the popup.html and popup.js files, trying show the YouTube video recommendations for the current user
popup.html:
<head>
<title>YouTube Recommendations</title>
<script src="oauth2/oauth2.js"></script>
<script src="popup.js"></script>
<style>
#success { display: none; }
</style>
</head>
<div id="loading">
Loading...
</div>
<div id="success">
<ul id="activities"></ul>
</div>
popup.js:
var google = new OAuth2('google', {
client_id: '{YOUR_CLIENT_ID}',
client_secret: '{YOUR_CLIENT_SECRET}',
api_scope: 'https://www.googleapis.com/auth/youtube'
});
google.authorize(function() {
var YOUTUBE_ACTIVITIES_URL = 'https://www.googleapis.com/youtube/v3/activities?part=id%2Csnippet%2CcontentDetails&home=true&maxResults=50&key=AIzaSyCx1xab1VHU7NdT6d2_x8i3p9RIZrtgR8k';
var loading = document.getElementById('loading');
var success = document.getElementById('success');
var activities = document.getElementById('activities');
// Make an XHR that retrieve activities with YouTube Data API
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(event) {
if (xhr.readyState == 4) {
if(xhr.status == 200) {
// Great success: parse response with JSON
var activitiesResponse = JSON.parse(xhr.responseText);
var items = activitiesResponse.items;
for (var i=0; i<items.length; i++) {
// Iterates over activities
var activity = items[i];
if ((activity.snippet.type == 'recommendation')&&(activity.contentDetails.recommendation.resourceId.videoId)){
activities.innerHTML += '<li>' + activity.snippet.title + '</li>';
}
}
loading.style.display = 'none';
success.style.display = 'block';
} else {
// Request failure: something bad happened
}
}
};
xhr.open('GET', YOUTUBE_ACTIVITIES_URL, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Authorization', 'OAuth ' + google.getAccessToken());
xhr.send();
});
Hi, I am developing a Google Chrome extension:
It is a dictionary that uses the Google translate API,When the user selects a text on the page I would like a popup to appear and show the selected text definition,
I have this code in my js file :
var req = new XMLHttpRequest();
req.open(
"GET",
"https://www.googleapis.com/language/translate/v2?" +
"format=html" +
"q=" + get_text_selection() + // Source Text
"source=en&" + // Source Language
"target=fa&" + // Target Language
true);
req.send(null);
function get_text_selection() {
if (window.getSelection)
return window.getSelection();
if (document.getSelection)
return document.getSelection();
if (document.selection)
return document.selection.createRange().text;
return '';
}
and this code in my Manifest.json file :
{
"name": "Google Translator",
"version": "1.0",
"manifest_version": 2,
"description": "This Extention helps you to translate text in your page",
"browser_action": {
"default_icon": "Dictionary-Book-icon.png",
"default_popup": "popup.html"
},
"permissions": [ "http://*/*", "https://*/*", "tabs" ]
}
and this code in my html file :
<!doctype html>
<html>
<head>
<title>Getting Started Extension's Popup</title>
<style>
body {
min-width:357px;
overflow-x:hidden;
}
</style>
<!-- JavaScript and HTML must be in separate files for security. -->
<script src="popup.js"></script>
</head>
<body>
</body>
</html>
but it's not working?
Where is my problem?
Thanks for your advice.
First of all Google Translate API is a paid service now. To use Google Translate API you need to get an API key from Google, you can get more information from here. After you get an API key your url should be like
"https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&source=en&target=fa&q=Hello%20world" // "Hello world" is query here
Which is in your case
"https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY" + "&format=html" + "&source=en" +"&target=fa" + "&q=" + get_text_selection()
Using following request (using my valid key from the browser address bar)
"https://www.googleapis.com/language/translate/v2?key=my_valid_key&format=html&q=home&source=en&target=fa" // I've replaced my key with my_valid_key
I've got this result
{ "error": { "errors": [ {
"domain": "usageLimits",
"reason": "dailyLimitExceeded",
"message": "Daily Limit Exceeded" } ],
"code": 403,
"message": "Daily Limit Exceeded"
}
}
Google Translate API no longer free and Translate API FAQ.