Why doesn't this chrome extension work? - javascript

I want to collect the url (var name is 'url') of a webpage into a variable in a chrome extension, together with several user inputs in text inputs, and to send it to a remote php script for processing into an sql database. I am using AJAX to make the connection to the remote server. The popup.html contains a simple form for UI, and the popup.js collects the variables and makes the AJAX connection. If I use url = document.location.href I get the url of the popup.html, not the page url I want to process. I tried using chrome.tabs.query() to get the lastFocusedWindow url - the script is below. Nothing happens! It looks as though it should be straightforward to get lastFocusedWindow url, but it causes the script to fail. The manifest.json sets 'tabs', https://ajax.googleapis.com/, and the remote server ip (presently within the LAN) in permissions. The popup.html has UI for description, and some tags. (btw the response also doesn't work, but for the moment I don't mind!)
//declare variables to be used globally
var url;
// Get the HTTP Object
function getHTTPObject(){
if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest) return new XMLHttpRequest();
else {
alert("Your browser does not support AJAX.");
return null;
}
// Change the value of the outputText field THIS PART IS NOT WORKING YET
function setOutput(){
if(httpObject.readyState == 4){
//document.getElementById('outputText').value = httpObject.responseText;
"Bookmark added to db" = httpObject.responseText; // does this work?
}
}
//put URL tab function here
chrome.tabs.query(
{"active": true, "lastFocusedWindow": true},
function (tabs)
{
var url = tabs[0].url; //may need to put 'var' in front of 'url'
}
);
// Implement business logic
function doWork(){
httpObject = getHTTPObject();
if (httpObject != null) {
//get url? THIS IS OUTSTANDING - url defined from chrome.tabs.query?
description = document.getElementById('description').value;
tag1 = document.getElementById('tag1').value;
tag2 = document.getElementById('tag2').value;
tag3 = document.getElementById('tag3').value;
tag4 = document.getElementById('tag4').value;
httpObject.open("GET", "http://192.168.1.90/working/ajax.php?url="+url+"&description="+description+"&tag1="+tag1+"&tag2="+tag2+"&tag3="+tag3+"&tag4="+tag4, true);
httpObject.send(null);
httpObject.onreadystatechange = setOutput(); //THIS PART IS NOT WORKING
finalString = httpObject.responseText; //NOT WORKING
return finalString; //not working
} //close if
} //close doWork function
var httpObject = null;
var url = null;
var description = null;
var tag1 = null;
var tag2 = null;
var tag3 = null;
var tag4 = null;
// listens for button click on popup.html
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('button').addEventListener('click', doWork);
});

Having no responses I first used a bookmarklet instead. The bookmarklet passes the url and title to a php script, which enters them into a db before redirecting the user back to the page they were on.
javascript:(function(){location.href='http://[ipaddress]/bookmarklet.php?url='+encodeURIComponent(location.href)+'&description='+encodeURIComponent(document.title)})()
Then I found this code which works a treat.
var urlOutput = document.getElementById('bookmarkUrl');
var titleOutput = document.getElementById('bookmarkTitle');
if(chrome) {
chrome.tabs.query(
{active: true, currentWindow: true},
(arrayOfTabs) => { logCurrentTabData(arrayOfTabs) }
);
} else {
browser.tabs.query({active: true, currentWindow: true})
.then(logCurrentTabData)
}
const logCurrentTabData = (tabs) => {
currentTab = tabs[0];
urlOutput.value = currentTab.url;
titleOutput.value = currentTab.title;
}

Related

How to switch url with javascript button

I'm trying to reuse a button in different landing pages and change the hyperlink of this button depending on what page is being browsed.
I started my function for it but I'm stuck on how to pass the data. If the user is on a page that contains home_ns in the url, I would like the button link to be cart1 and if the user is on a page called home_nd I would like it to be cart 2.
<script type="text/javascript">
var cart1 = '/?add-to-cart=2419';
var cart2 = '/?add-to-cart=2417';
function urlCart() {
if(window.location.href.indexOf("home_ns") > -1) {
// This is where I am stuck
}
}
</script>
Then the button will be
<button onclick="urlCart()">Order Now</button>
Here is what you need:
var cart1 = '/?add-to-cart=2419';
var cart2 = '/?add-to-cart=2417';
function urlCart() {
if(window.location.href.indexOf("home_ns") > -1) {
window.location.href = cart1;
} else {
window.location.href = cart2;
}
}
You could create a look-up map of pages to cart ID. You can then update the search parameter in the URL to reflect the found ID.
Note: Since the Stack snippet below is not going to actually have the correct href, the code will not add/update the parameter. If you want to integrate this, replace the url variable declaration with this:
let url = window.location.href;
You could also use the pathname instead of the href for finer granularity.
let url = window.location.pathname;
// See: https://stackoverflow.com/a/56593312/1762224
const setSearchParam = function(key, value) {
if (!window.history.pushState) return;
if (!key) return;
let url = new URL(window.location.href);
let params = new window.URLSearchParams(window.location.search);
if (value === undefined || value === null) params.delete(key);
else params.set(key, value);
url.search = params;
url = url.toString();
window.history.replaceState({ url: url }, null, url);
}
const pageMap = {
"home_ns": 2419,
"home_nd": 2417
};
function urlCart() {
let url = 'https://mywebsite.com/home_ns' || window.location.href;
Object.keys(pageMap).some(page => {
if (url.includes(page)) {
console.log('Found page:', page);
setSearchParam('add-to-cart', pageMap[page]);
return true;
} else {
return false;
}
});
}
<button onclick="urlCart()">Order Now</button>
Simply you can move the user to another page by:
location.href = myURL;
The browser will automatically go to the specified page.
Examples of what a URL can be:
An absolute URL - points to another web site (like
location.href="http://www.example.com/default.htm")
A relative URL - points to a file within a web site (like location.href="default.htm")
An anchor URL - points to an anchor within a page (like
location.href="#top")
A new protocol - specifies a different protocol
(like location.href="ftp://someftpserver.com",
location.href="mailto:someone#example.com" or
location.href="file://host/path/example.txt")
Source

UPDATED: redirect url pass parameter from another page

I'm would like to do a 2 step process without the user knowing. Right now when the user click on the link from another page.
URL redirect to run some JavaScript function that updates the database.
Then pass the variable to view a document.
User clicks on this link from another page
Here is some of code in the JavaScript file:
<script type="text/javascript">
window.onload = function(){
var auditObject ="";
var audit_rec = {};
var redirLink = "";
if(document.URL.indexOf('?1w') > -1 {
redirLink = "https://www.wikipedia.org/";
auditObject = redirLink;
audit_rec.action = "OPEN";
audit_rec.object = auditObject;
audit_rec.object_type = "WINDOW";
audit_rec.status = "Y";
window.open(redirLink);
} else {
audit_rec.target = /MyServlet;
audit_rec.action = "OPEN";
audit_rec.object = TESTSITE;
audit_rec.object_type = "WINDOW";
audit_rec.status = "Y";
}
function audit(audit_rec) {
var strObject = audit_rec.object;
strObject = strObject.toLowerCase();
var strCategory = "";
if (strObject.indexOf("wiki") > -1) {
strCategory = "Wiki";
} else if strObject.indexOf("test") > -1) {
strCategory = "TEST Home Page";
}
//Send jQuery AJAX request to audit the user event.
$.post(audit_rec.target, {
ACTION_DATE : String(Date.now()),
DOMAIN : "TESTSITE",
ACTION : audit_rec.action,
OBJECT : audit_rec.object,
OBJECT_TYPE : audit_rec.object_type,
STATUS : audit_rec.status
});
}
//TEST initial page load.
audit(audit_rec);
}
</script>
Can someone help? Thanks
You could give your link a class or ID such as
<a id="doclink" href="http://website.com/docviewer.html?docId=ABC%2Fguide%3A%2F%2F'||i.guide||'">'||i.docno||'</a>
then use javascript to intercept it and run your ajax script to update the database. Here's how you'd do it in jQuery:
$('#doclink').click(function(e) {
var linkToFollow = $(this).attr('href');
e.preventDefault();
yourAjaxFunction(parameters, function() {
location.href = linkToFollow;
});
});
where the function containing the redirect is a callback function after your ajax script completes. This stops the link from being followed until you've run your ajax script.
if your question is to hide the parameters Here is the Answer
you just use input type as hidden the code like this
'||i.docno||'

Submit form from loaded tab in Firefox Addon SDK?

I'm trying to make a FF addon which could open new tab, load page with login form and submit this form. The main issue is that there a lot of additional parameters also must be sent. So I cannot simulate this POST-request exactly with XMLHttpRequest and content scripts. Instead of this I just want to get the form via DOMParser, set login and password in input fields and send it via form.submit(), but nothing happens. Here is the code:
const windowUtils = require("sdk/window/utils");
var {Cc, Ci} = require("chrome");
var DOMPars = Cc["#mozilla.org/xmlextras/domparser;1"].createInstance(Ci.nsIDOMParser);
var gBrowser = windowUtils.getMostRecentBrowserWindow().getBrowser();
var newTab = gBrowser.addTab("https://some-page-url");
var newTabBrowser = gBrowser.getBrowserForTab(newTab);
var contentdata = "";
newTabBrowser.addEventListener("load", function () {
contentdata = contentdata + newTabBrowser.contentDocument.body.innerHTML;
var dom = DOMPars.parseFromString(contentdata, "text/html");
var login_form = dom.getElementsByName('login_form_name');
if(typeof login_form !== "undefined"){
dom.getElementsByName('user_login').value = 'user_login_here';
dom.getElementsByName('user_pass').value = 'user_pass_here';
login_form.submit();
}
}, true);
Is it possible to do it in this way? Thanks!

Urls in creating chrome extension tabs do not work

I am creating a chrome extension which access a api and parses the json feed to get data. One of the data is a link and I want the link to be opened in a new tab. I use chrome.create.tabs to do it. But instead of opening a tab with specified url it opens like this
chrome-extension://app_id/%22http://www.twitch.tv/imaqtpie%22
Here is my popup.js
document.addEventListener('DOMContentLoaded', init);
function init(){
var elem = document.getElementById('Add');
elem.addEventListener('click',func);
}
function func(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.twitch.tv/kraken/search/streams?q=league%20of%20legends", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// innerText does not let the attacker inject HTML elements.
var qtpie=JSON.parse(xhr.responseText);
var display_name = JSON.stringify(qtpie.streams[0].channel.display_name);
var stream_status = JSON.stringify(qtpie.streams[0].channel.status);
var stream_url=JSON.stringify(qtpie.streams[0].channel.url);
var res = display_name+" : "+stream_status+"\n"+stream_url;
console.log(stream_url);
var a = document.createElement('a');
var linkText = document.createTextNode(res);
a.appendChild(linkText);
a.setAttribute('href', stream_url);
a.addEventListener('click', link_handler(stream_url));
document.getElementById("status").appendChild(a);
var magic=activateLinks();
// document.getElementById("status").innerText = res;
}
}
xhr.send();
}
function activateLinks()
{
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
(function () {
var ln = links[i];
var location = ln.href;
ln.onclick = function () {
chrome.tabs.create({active: true, url: location});
};
})();
}
}
function link_handler(url)
{
// Only allow http and https URLs.
if (url.indexOf('http:') != 0 && url.indexOf('https:') != 0) {
return;
}
chrome.tabs.create({url: url});
}
Here stream_url is the variable that stores the parsed url from json.
here is the json from which it is parsed from
"video_banner":null,
"background":null,
"profile_banner":null,
"profile_banner_background_color":null,
"partner":true,
"url":"http://www.twitch.tv/imaqtpie",
"views":91792487
i want the new tab to open http://www.twitch.tv/imaqtpie instead of chrome-extension://app_id/%22http://www.twitch.tv/imaqtpie
. Thanks in advance. Btw using <base href="http://" target="_blank"> does not work.
So the problem is for the url. Your url is improper when using chrome.tabs.create, because %22 indicates the character " in ASCII Encoding Reference. You should strip it off in the url when you get the element in html. Glad it helps!

Javascript XMLHTTPRequest Not Posting XML File

I have a content generator which contians textboxes, textareas and file input controls. All controls are in HTML. Once the save button is clicked I create my XML Document with the text entered into the HTML controls. Finally, I would like the user to be prompted to download the XML File. I am hoping I can do this using a POST method with a XMLHTTPRequest in Javascript. Once the XML Document is sent with the XMLHTTPRequest here is what happens,
Chrome: HTTP Status Code: 304
IE10: Nothing happens
Again, I would like the browser to prompt the user to download the XML File. Here is my code.
function generateBaseNodes() {
var xmlString = '<?xml version="1.0"?>' +
'<sites>' +
'<site>' +
'<textareas>' +
'</textareas>' +
'<textboxes>' +
'</textboxes>' +
'<images>' +
'</images>' +
'</site>' +
'</sites>';
if (window.DOMParser) {
parser = new DOMParser();
xmlDocument = parser.parseFromString(xmlString, "text/xml");
}
else // Internet Explorer
{
xmlDocument = new ActiveXObject("Microsoft.XMLDOM");
xmlDocument.async = false;
xmlDocument.loadXML(xmlString);
}
return xmlDocument;
}
function saveXmlFile(xmlDocument) {
if (window.XMLHttpRequest) { // IE7+, Chrome. Firefox, Opera. Safari
xmlhttp = new XMLHttpRequest();
}
else { // IE5 & IE6
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open('POST', 'http://localhost:57326/ContentGenerator.html', true);
xmlhttp.setRequestHeader('Content-type','text/xml');
xmlhttp.send(xmlDocument);
}
$('document').ready(function () {
$('#templateTab a').click(function (e) {
e.preventDefault()
$(this).tab('show')
})
//Create TextArea XML elements and add them
$('#btnSave').click(function () {
var x;
var xmlDocument = generateBaseNodes();
$('.content').each(function () { // Textarea
if ($(this).attr('id') != undefined) {
if ($(this).is('textarea')) {
// create article node with control id.
articleNode = xmlDocument.createElement($(this).attr('id'));
// append node to xmldocument
x = xmlDocument.getElementsByTagName('textareas')[0];
x.appendChild(articleNode);
// append text
articleNode.appendChild(xmlDocument.createTextNode($(this).text()));
}
if ($(this).is('input[type=text]')) { // Textbox
textNode = xmlDocument.createElement($(this).attr('id'));
x = xmlDocument.getElementsByTagName('textboxes')[0];
x.appendChild(textNode);
textNode.appendChild(xmlDocument.createTextNode($(this).text()));
}
} else { // Show error if a control does not have an ID assigned to it.
alert('The' + $(this).prop('type') + 'has an undefined ID.');
}
});
$('.imageContent').each(function () {
if ($('.imageContent input[type=file]')) { // Image url
// Validate file is an image
switch ($(this).val().substring($(this).val().lastIndexOf('.') + 1).toLowerCase()) {
case 'gif': case 'jpg': case 'png':
imageNode = xmlDocument.createElement($(this).attr('id'));
x = xmlDocument.getElementsByTagName('images')[0];
x.appendChild(imageNode);
imageNode.appendChild(xmlDocument.createTextNode($(this).val()));
break;
default:
$(this).val('');
// error message here
alert("not an image");
break;
}
}
});
saveXmlFile(xmlDocument);
});
});
I SUPPOSE I SHOULD POST MY XML OUTPUT
<sites>
<site>
<textareas>
<article1>sfdsfd</article1>
<article2>dsfsdf</article2>
</textareas>
<textboxes>
<title>dsfdsf</title>
<contentHeader>sdfsdf</contentHeader>
<linkContent>sdf</linkContent>
<link>sdfsd</link>
<relatedContent>sdfsdf</relatedContent>
<contentLink>dsf</contentLink>
<relatedArticle>sdfa</relatedArticle>
<articleLink>sfdf</articleLink>
</textboxes>
<images>
<imageHeader>C:\Images\Header.png</imageHeader>
<articleImage>C:\Images\Main.png</articleImage>
<articleImage2>C:\Images\Deals.png</articleImage2>
</images>
</site>
</sites>
Is there any way to make the browser prompt to download the XML File?
Yep. Convert your data to Blob, then generate a URL from it, which you can then use in an <a>, give that <a> a download attribute and the browser now knows it's to be saved not opened, then finally simulate a click on it. For example;
function txtToBlob(txt) {
return new Blob([txt], {type: 'plain/text'});
}
function genDownloadLink(blob, filename) {
var a = document.createElement('a');
a.setAttribute('href', URL.createObjectURL(blob));
a.setAttribute('download', filename || '');
a.appendChild(document.createTextNode(filename || 'Download'));
return a;
}
function downloadIt(a) {
return a.dispatchEvent(new Event('click'));
}
// and use it
var myText = 'foobar',
myFileName = 'yay.txt';
downloadIt(
genDownloadLink(
txtToBlob(myText),
myFileName
)
);
Try using Filesaver.js to get the user to download a file in memory.
Look also into Data URI's like this:
text file

Categories

Resources