cross_origin error for chrome extension - javascript

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.

Related

Uncaught TypeError: Cannot read property 'isAvailable' of undefined;

I am trying to get the tutorial from Cordova GooglePlus to work. I havent spent about 16 hours on it over the past 3 days, combing stackoverflow, google, and github and I've come far but I keep getting an uncaught type error. It seems that I am not referencing the functions in GooglePlus.js correctly. Any tips would be appreciated. Here's the apk I created, which gives the same errors App.apk
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="format-detection" content="telephone=no"/>
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height"/>
<link rel="stylesheet" type="text/css" href="css/index.css"/>
<meta name="msapplication-tap-highlight" content="no"/>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="plugins/cordova-plugin-googleplus/www/GooglePlus.js"></script>
<title>Hello World</title>
<script type="text/javascript">
app.initialize();
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
function isAvailable() {
window.plugins.googleplus.isAvailable(function(avail) {alert(avail)});
}
function login() {
window.plugins.googleplus.login(
{},
function (obj) {
document.querySelector("#image").src = obj.imageUrl;
document.querySelector("#image").style.visibility = 'visible';
document.querySelector("#feedback").innerHTML = "Hi, " + obj.displayName + ", " + obj.email;
},
function (msg) {
document.querySelector("#feedback").innerHTML = "error: " + msg;
}
);
}
function trySilentLogin() {
window.plugins.googleplus.trySilentLogin(
{},
function (obj) {
document.querySelector("#image").src = obj.imageUrl;
document.querySelector("#image").style.visibility = 'visible';
document.querySelector("#feedback").innerHTML = "Silent hi, " + obj.displayName + ", " + obj.email;
},
function (msg) {
document.querySelector("#feedback").innerHTML = "error: " + msg;
}
);
}
function logout() {
window.plugins.googleplus.logout(
function (msg) {
document.querySelector("#image").style.visibility = 'hidden';
document.querySelector("#feedback").innerHTML = msg;
},
function (msg) {
document.querySelector("#feedback").innerHTML = msg;
}
);
}
function disconnect() {
window.plugins.googleplus.disconnect(
function (msg) {
document.querySelector("#image").style.visibility = 'hidden';
document.querySelector("#feedback").innerHTML = msg;
},
function (msg) {
document.querySelector("#feedback").innerHTML = msg;
}
);
}
window.onerror = function(what, line, file) {
alert(what + '; ' + line + '; ' + file);
};
function handleOpenURL (url) {
document.querySelector("#feedback").innerHTML = "App was opened by URL: " + url;
}
</script>
</head>
<body onload="onLoad">
<div class="app">
<img id="image" style="position:absolute; top:10px; left:10px" src="" />
<h1>Google+</h1>
<div id="deviceready" class="blink">
<p class="event listening">Connecting to Device</p>
<p class="event received">Device is Ready</p>
<p id="feedback">not logged in</p>
<button onclick="isAvailable()">Available?</button>
<br/><br/>
<button onclick="login()">Login with Google+</button>
<br/><br/>
<button onclick="trySilentLogin()">Try silent login with Google+</button>
<br/><br/>
<button onclick="logout()">Logout</button>
<button onclick="disconnect()">Disconnect</button>
<br/><br/>
<button onclick="window.plugins.googleplus.getSigningCertificateFingerprint(function(res){alert(res)}, function(res){alert(res)})">get cert fingerprint (Android)</button>
</div>
</div>
</body>
</html>
At a glance, it looks like you may be missing an identifier in the chain.
Your isAvailable() function:
window.plugins.isAvailable(...);
vs repo's:
window.plugins.googleplus.isAvailable(...);
The scripts in your code have relative paths so I can't test it, but googleplus is present elsewhere in your code, specifically as a property of window.plugins, so I'm guessing that's the culplrit.

Open current page URL in new window when click on chrome extension icon

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);

JS automated click not working

EDIT:
I think i have found a solution for this one. Might be a little primitive but inserting it here until someone comes up with a better solution.
Thanks !
<html>
<body onload="makeShort()">
<p id="button" style=display:none; onclick="makeShort()">Click me.</p>
<span id="output" style=display:none; >Wait. Loading....</span>
</body>
<head>
</head>
<script type="text/javascript">
function makeShort()
{
var longUrl=location.href;;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response)
{
if(response.id != null)
{
str =""+response.id+"";
document.getElementById("output").innerHTML = str;
}
else
{
alert("error: creating short url n"+ response.error);
}
});
}
window.onload = makeShort;
function load()
{
//Get your own Browser API Key from https://code.google.com/apis/console/
gapi.client.setApiKey('xxxxxx');
gapi.client.load('urlshortener', 'v1',function(){document.getElementById("output").innerHTML="";});
}
window.onload = load;
</script>
<script>
setTimeout(function(){
document.getElementById('button').click();
},1000);
</script>
<script src="https://apis.google.com/js/client.js"> </script>
</html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<script>
function SendLinkByMail(href) {
var subject= "Interesting Information";
var body = document.getElementById("output").innerHTML;
body += " Interesting Information";
var uri = "mailto:?subject=";
uri += encodeURIComponent(subject);
uri += "&body=";
uri += encodeURIComponent(body);
window.open(uri);
}
</script>
</head>
<body>
<p>Email link to this page</p>
</body>
</html>
Can some one suggest why this "auto-click" function is not working in my code below?
function makeShort() {
var longUrl = location.href;;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response) {
if (response.id != null) {
str = "<b>Long URL:</b>" + longUrl + "<br>";
str += "<b>Short URL:</b> <a href='" + response.id + "'>" + response.id + "</a><br>";
document.getElementById("output").innerHTML = str;
} else {
alert("error: creating short url n" + response.error);
}
});} window.onload = function() {
var button = document.getElementById('modal');
button.form.submit();}
function load() {
//Get your own Browser API Key from https://code.google.com/apis/console/
gapi.client.setApiKey('xxxxxxxxx');
gapi.client.load('urlshortener', 'v1', function() {
document.getElementById("output").innerHTML = "";
});} window.onload = load;
<html>
<input type="button" id="modal" value="Create Short" onclick="makeShort();" /> <br/> <br/>
<div id="output">Wait. Loading....</div>
<head>
</head>
<script src="https://apis.google.com/js/client.js"> </script>
</html>
My basic aim is to insert a "share via email" button on the page which would shorten the url on the address bar and open user's email client/whatsapp app to share that url..
Obviously I could not find a way to combine these two functions in to one since I am not a very experienced js person. The primitive solution I found is to auto-click the first function, get the short url, and then find a different code to insert this in to the body of the "mailto" link, which will be my 2nd challenge.
To programmatically click a button on page load
If you are using jQuery:
$(function() {
$('#modal').click();
});
Plain javascript:
window.onload = function(){
var event = document.createEvent('Event');
event.initEvent('input', true, true);
document.getElementById("modal").dispatchEvent(event);
};

why my command not showing up the popup with a input field?

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>

Google URL shortener API - Uncaught TypeError: undefined is not a function

I am following the google URL shortner API tutorial from this site:
http://hayageek.com/google-url-shortener-api/
I am following along and this is my code:
<html>
<head>
</head>
<script type="text/javascript">
function makeShort()
{
var longURL=document.getElementByID("longurl").value; //error here
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longURL
}
});
request.execute(function(response)
{
if(response.id != null)
{
str = "<b>Long URL:</b>" +longURL+ "<br>";
str += "<b>Short URL:</b> <a href='"+response.id+ "'>"+response.id+"</a><br>";
document.getElementByID("output").innerHTML = str;
}
else
{
alert("error: creating short url n"+ response.error);
}
});
}
function getShortInfo()
{
var shortURL = document.getElementByID("shortURL").value;
var request = gapi.client.urlshortener.url.get({
'shortUrl':shortURL,
'projection':'FULL'
});
request.execute(function(response)
{
if(response.longURL!=null)
{
str ="<<b>Long URL</b>"+response.longURL+"<br>";
str += "<b>Create On:</b>"+response.created+"<br>";
str +="<b>Short URL Clicks:</b>"+response.analytics.allTime.shortUrlClicks+"<br>";
str +="<b>Long URL Clicks:</b>"+response.analytics.allTime.longUrlClicks+"<br>";
document.getElementByID("output").innerHTML = str;
}
else
{
alert("error: "+response.error);
}
});
}
function load()
{
gapi.client.setApiKey('APIKEYISHERE');
gapi.client.load('urlshortener', 'v1',function(){document.getElementById("output").innerHTML="";});
}
window.onload = load;
</script>
<script src="https://apis.google.com/js/client.js"></script>
<body>
URL: <input type="text" id="longurl" name="url"/> <br/>
<input type="button" value="Create Short URL" onclick="makeShort()" /> <br/> <br/>
URL: <input type="text" id="shorturl" name="url"/> <br/>
<input type="button" value="Get Short URL info" onclick="getShortInfo()"/>
<div id="output">Wait. Loading... </div>
</body>
</html>
However, when I try to run the URL shortener, it gives me an "Uncaught TypeError: undefined is not a function" error on line 8.
Not sure what I'm doing wrong here... I am a beginner programmer.
Change :
var longURL=document.getElementByID("longurl").value; //error here
To :
var longURL=document.getElementById("longurl").value; //Solved
I Figured it out,
getElementByID should be getElementById
Change :
var longURL=document.getElementByID("longurl").value; //error here
To :
var longURL=document.getElementById("longurl").value; //Solved

Categories

Resources