Chrome addon with my server interaction - google-chrome

its many days reading hundreds of ways to help me make what I really need. No success at all.
What I need is this:
1) Having a button which only works when the tab has a certain url.
2) After clicking it, must read page's source and then get some pieces of it to send them to my server page in order to check my database for recordcounts (I assume with AJAX & javascript). Then this page should send back to the extension its responses and populate the popup html.
Looks easy I know, but please I need the workflow if not the required codes for the extension.
Thank you so much!

ok so you can chceck selected tab and it's url with:
chrome.tabs.getSelected(null,function(tab) {
workWithUrl(tab.url);
});
...
function workWithUrl(url){
if (url == ...
...
}
To be able to chceck this you need to add permission for "tabs"
To process page source code, send it to web service and change popup.html:
var xhr = new XMLHttpRequest();
xhr.open("POST", "__server adress___", true);
//headers
xhr.setRequestHeader("Content-Type", "application/json");
//response
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
//response from service to popup.html
document.body.innerHTML = xhr.responseText;
}
}
//process page here
xhr.send(pageText);
You have to add permission for server adress to manifest as well and everything should be executed from popup.js (or html).

Related

Can i send data from one website’s console to another?

So im trying to automate a task at work, and im wondering if theres anyway to send data from the console of one webpage to the console of another web page.
The task i am trying to automate consists of a website that has a prefilled form. I need to get elements from this form, and then copy them into another totally different website. Ive already written a script that pulls the data i need from the form and displays it in the console. Now I need to find a way to send the data (which is simply variables) to the other page’s console. Is this possible?
Keep in mind this is in a work computer, not allowed to download anything on it.
Are you an admin of the webpages and are these pages from the same site? if the answer is yes, i would recommend you use localStorage for saving and retrieving the data then display it to the console.
If it's not your website and you want it to work anyway just create a simple browser extension.
Here are some links to help you get started with extensions
MDN doc
Chrome doc
The idea is for you to target webpage A collect the data and post it to Github
Then target webpage B to read data from your github gist and you dispaly it in the console.
Cheers, i hope it was helpfull
Which server side language are you using ?
Usually for these, you could just have a form which is posting data to another website's form.
Look at this php example :
https://www.ostraining.com/blog/coding/retrieve-html-form-data-with-php/
Correct me If I did not understand your question correctly.
//Store the logs in following way
console.stdlog = console.log.bind(console);
console.logs = [];
console.log = function(){
console.logs.push(Array.from(arguments));
console.stdlog.apply(console, arguments);
}
//copying the logs into a json file
(function(console){
console.save = function(data, filename){
if(!data) {
console.error('Console.save: No data')
return;
}
if(!filename) filename = 'console.json'
if(typeof data === "object"){
data = JSON.stringify(data, undefined, 4)
}
var blob = new Blob([data], {type: 'text/json'}),
e = document.createEvent('MouseEvents'),
a = document.createElement('a')
a.download = filename
a.href = window.URL.createObjectURL(blob)
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
a.dispatchEvent(e)
}
})(console)
console.save(console.logs) //prints the logs in console.json file
// from the console.json file, you can use log information from another page
//Store the logs in following way
console.stdlog = console.log.bind(console);
console.logs = [];
console.log = function(){
console.logs.push(Array.from(arguments));
console.stdlog.apply(console, arguments);
}
localStorage.setItem('Logs', console.logs);
localStorage.getItem('Logs'); // from any browser

How to make Web page to not wait for a response after sending a GET request

I am trying to make this web site that resides in Google Drive control a LED(on/off) via esp8266 and arduino. Partially i've succeded in doing what i want by sending to the IP of the module that communicates with the arduino a GET request witch parses it and acts accordingly. ie GET /?LED1=on HTTP/1.1
Problem is that whenever i press a button in the web site it sends the GET request and then it waits for a response from the other end (arduino),and the browser keeps loading until eather I close the connection from the arduino or I reply something like HTTP/1.1 200 OK and then close the conection.
In the first case browser shows the message that was unable to load the page and in second case it simply shows a blank page.
<DOCTYPE html>
<html>
<head>
<title>LED Control</title>
</head>
<body>
<button>LED 1 On</button>
</body>
</html>
I just want to send that LED1=on string somehow without causing the page attempt to load anything back.
A reusable solution
Modify your HTML to be something like this:
<button class="get" data-url="http://78.87.xxx.xx:333/?LED1=on">LED 1 On</button>
Now add this JavaScript:
window.onload = function () {
Array.prototype.forEach.call(document.querySelectorAll('.get'), function(el) {
el.onclick = function () {
// Use this trick to perform CORS requests too
var req = new Image();
req.src = this.dataset.url;
// The following 7 lines are completely optional
req.onload = function () {
// Was successful
};
req.onerror = function (error) {
// Encountered an error
alert('An error occurred while performing the request. + ' error);
};
};
});
};
Now any element with the class "get" when clicked, will send a request to the URL. This won't change the page either. If

xmlHttpRequest to absolute url in WP8

I have stumbled across an odd issue when testing an app in Windows Phone 8. I am using xmlHttpRequest (cannot use ajax as I need to send as bufferarray) to make a call to a third party url. This works perfectly in Android and iOS, but throws an error in WP8
Example:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function (){
if(xhr.readyState == 4){
if(xhr.status==200){
alert(xhr.responseText);
}else{
console.log("Error: "+xhr.responseText);
}
}
}
console.log("1");
xhr.timeout = 30000;
console.log("2");
xhr.open("POST","http://google.com",true);
console.log("3");
xhr.setRequestHeader("Content-Type",contentType+"; boundary=" + boundary);
console.log("4");
//other headers / auth etc
console.log("about to post");
xhr.send(bodyBuf);
this will result in:
log:"before request"
log:"1"
log:"2"
log:"Error in error callback: Cameraxxxxx = InvalidStateError"
However if I chang the open to:
xhr.open("POST","google.com",true); //or www.google.com etc
This goes right through to send, but then get a 404 status as the url is not found. I am obviously not using google in my request, but the error is the same. With "http://" it errors, but without, it doesn't error but cannot find the url.
Any thoughts appreciated.
I have found one thing, but unsure if it is related. According to W3C html 5 documentation, InvalidStateError is thown on open() if document is not fully active (when it is the active document of its browsing context). And if this is the cause of the error; how can the document not be the active document and how to I define the base url of an app that does not reside on a url (document suggests setting base to the document base url of document (or setting source origin/referrer source))?
Have gotten one step closer. After lots of fiddling about, I eventually found that for some reason on WP8 is needs the xhr to be opened before anything else is applied. So moving xhr.timeout below xhr.open sort of works.
this raises another problem in my particular case.. but that is probably another topic.
Solution for this was to move the timout to below the open.. so:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function (){
if(xhr.readyState == 4){
if(xhr.status==200){
alert(xhr.responseText);
}else{
console.log("Error: "+xhr.responseText);
}
}
}
xhr.open("POST","http://google.com",true);
xhr.timeout = 30000;
xhr.setRequestHeader("Content-Type",contentType+"; boundary=" + boundary);
//other headers / auth etc
xhr.send(bodyBuf);

Chrome Extension: Insert a clickable image using a content script

I know hat it is possible, but I am not quite sure how to do it the 'right' way, as to ensure there are no conflicts.
I came across this question: Cannot call functions to content scripts by clicking on image . But it is so convoluted with random comments that it's hard to understand what the corrected way was.
Use case:
Html pages have a div on the page where they expect anyone using the Chrome extension to inject a picture. When users click on he picture, I want to somehow notify an event script. So I know I need to register a listener so the code inserted messages the event script.
Can I get some indication on what code to inject through the content script? I saw that sometimes injecting jquery directly is advised.
I am trying to avoid having the html page to post a message to itself so it can be intercepted. Thanks
With the help of Jquery something like this would capture the image onclick event and allow you to pass a message to a background page in the Chrome Extension:
$("img").click(function(){
var imageSrc = $(this).attr("src");
//Post to a background page in the Chrome Extension
chrome.extension.sendMessage({ cmd: "postImage", data: { imgSrc: imageSrc } }, function (response) {
return response;
});
});
Then in your background.js create a listener for the message:
chrome.extension.onMessage.addListener(
function (request, sender, sendResponse) {
if (request.cmd == "postImage") {
var imageSrc = request.data.imgSrc;
}
});

Chrome extension: how to constantly check URLs on new tabs and then respond with an action for certain URLs?

Hi—I'm not a student or a programmer by trade, but I'm trying to knock up a quick prototype to get an idea across. I've cobbled together some code from other StackOverflow questions, and I've almost got what I need, but I'm having trouble with one thing: the extension will run exactly once, but no more, until I refresh the extension via chrome://extensions. I'm guessing there's something wrong with the element of this program that listens for a new URL, but I can't figure out how to keep that element listening constantly. This code runs in background.js right now, though I've also tried it in background.html.
Basically, I'd like the extension to check the URL of a tab any time the user visits a new page (either by typing the URL herself or clicking through to one), and, if the URL appears in the plugin's internal URL list, to pop up a short notification. I have this so far:
// Called when the url of a tab changes.
// So we can notify users
var notification = webkitNotifications.createNotification(
'48.png',
'Alert!'
);
// Called when the url of a tab changes.
function checkForValidUrl(tab) {
// Compare with a the URL
if (tab.url.match(/google/)) {
//then
notification.show();
}
};
// Listen for any changes to the URL of any tab.
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
if(changeInfo.status == "loading") {
checkForValidUrl(tab);
}
});
chrome.tabs.onSelectionChanged.addListener(function(tabId, selectInfo){
chrome.tabs.getSelected(null, function(tab){
checkForValidUrl(tab);
});
});
I fixed this after hacking it around a little bit -- I don't really have the vocabulary to explain what I did but I thought I'd post the code in case someone else has the same (simple) problem later.
function checkForValidUrl(tabId, changeInfo, tab) {
var notification = webkitNotifications.createNotification(
'48.png',
'Alert!',
'Watch out for your privacy!'
);
// Compare with the URL
if (tab.url.match(/google/)) {
//then
notification.show();
}
};
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
if(changeInfo.status == "loading") {
checkForValidUrl(tabId, changeInfo, tab);
}
});