I'm trying to create chrome extension which check if site contains specific element, then clear cookies for this site and refresh.
I created sample extension to delete cookies but in background.js using event chrome.browserAction.onClicked.addListener, :
chrome.browserAction.onClicked.addListener(function(tab) {
var url = tab.url;
var matches = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
var d = matches && matches[1].replace('www.','');
d = '.'+d;
chrome.cookies.getAll({domain: d}, function (cookies) {
for (var i=0; i<cookies.length; i++) {
var url = "http" + (cookies[i].secure ? "s" : "") + "://" + cookies[i].domain + cookies[i].path;
var cname = cookies[i].name;
chrome.cookies.remove({
"url": url,
"name": cname
});
}
chrome.tabs.reload();
});
});
I took this code from one of posts on stackoverflow, and I was trying to transform it for my need.
In my main extension in background.js I have:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
chrome.tabs.getSelected(null, function(tab){
chrome.tabs.executeScript(null, {file: 'script.js'});
});
});
and then in script.js:
..some code...
var test = document.getElementById('u_0_c');
if (test === null || test.innerText == "") {
/*------------------------------*/
HERE I WANT TO CLEAR COOKIES
/*----------------------------*/
}
..some code...
I can't use there my code to clear cookies because I got errors like:
Cannot read property 'getSelected' of undefined and similiars.
Thanks for every help ;)
Related
I want two types of domain redirects on the same site (if else statement etc):
If user has cookie:
And url subdomain is amazon then redirect to url xxxxxx
And url subdomain is ebay then redirect to url xxxx
If user has no cookie:
And url subdomain amazon then first forward to ebay subdomain and back to amazon subdomain once (currently creates a loop) and display background xxxx with href link xxxx
And url subdomain ebay then first forward to amazon subdomain and back to ebay subdomain once (currently creates a loop) and display background xxxx with href link xxxx
Synchronise user cross-domain click for a new pop-up for href xxxxx - ie if user has come on site by clicking on link on another site then see asynchronise click to open another pop-up (200 sec rule)
Currently site already has below which I still need, so cookie redirect shouldn't set a redirect to site outside because of the code below but only if user is genuinely a returning user
var subdomain = window.location.hostname.split('.')[0];
if (!document.cookie == null && subdomain === "amazon") {
window.location = "http://www..com";
} else if (!document.cookie == null && subdomain === "ebay") {
window.location = "http://www.tutorialspoint.com";
} else if (document.cookie == null && subdomain === "amazon") {
var oLinksArray = [];
oLinksArray[0] = 'http://www.ebay.com';
oLinksArray[1] = 'http://www.amazon.com';
for (var x = 0; x < 2; x++) {
var openWindow = window.open(oLinksArray[x]);
setTimeout(function() {
openWindow.close();
}, 2000);
}
} else if (document.cookie == null && subdomain === "ebay") {
var oLinksArray = [];
oLinksArray[0] = 'http://www.amazon.com';
oLinksArray[1] = 'http://www.ebay.com';
for (var x = 0; x < 2; x++) {
var openWindow = window.open(oLinksArray[x]);
setTimeout(function() {
openWindow.close();
}, 2000);
}
} else {}
You don't need to transfer cookie with redirection. Cookie has a property called domain. You should add website's domains to give access permission to them.
In Javascript
var cookieName = 'HelloWorld';
var cookieValue = 'HelloWorld';
var myDate = new Date();
myDate.setMonth(myDate.getMonth() + 12);
document.cookie = cookieName +"=" + cookieValue + ";expires=" + myDate
+ ";domain=firstDomain.com,nextDomain.com;path=/";
In PHP
setcookie('mycookie','mydata1',time() + 2*7*24*60*60,'/','www.firstDomain.com,nextDomain.com', false);
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;
}
Hi I am developing one application in java-script. I have two pages default.aspx and addnewitem.aspx. there is one html table in default.aspx and one button. When i click on button i want to redirect to addnewitem.aspx page. I have some parameters to send in query string. I am able to redirect to addnewitem.aspx but page not found error i am getting. I am not sure why i am getting page not found error. I am trying as below.
function getValues() {
var Title = "dfd";
var PrimarySkills = "fdfd";
var SecondarySkills = "dfdf";
var url = "http://sites/APPSTEST/JobRequisitionApp/Pages/AddNewItem.aspx?Title=" + encodeURIComponent($(Title)) + "&PrimarySkills=" + encodeURIComponent($(PrimarySkills)) + "&SecondarySkills=" + encodeURIComponent($(SecondarySkills));
window.location.href = url;
}
I am checking querystring in addnewitem.aspx as below.
<script type="text/javascript">
var queryString = new Array();
$(function () {
if (queryString.length == 0) {
if (window.location.search.split('?').length > 1) {
var params = window.location.search.split('?')[1].split('&');
for (var i = 0; i < params.length; i++) {
var key = params[i].split('=')[0];
var value = decodeURIComponent(params[i].split('=')[1]);
queryString[key] = value;
}
}
}
if (queryString["Title"] != null && queryString["PrimarySkills"] != null) {
var data = "<u>Values from QueryString</u><br /><br />";
data += "<b>Title:</b> " + queryString["Title"] + " <b>PrimarySkills:</b> " + queryString["PrimarySkills"] + " <b>SecondarySkills:</b> " + queryString["SecondarySkills"];
$("#lblData").html(data);
alert(data);
}
});
</script>
"http://sites/APPSTEST/JobRequisitionApp/Pages/AddNewItem.aspx?Title=%5Bobject%20Object%5D&PrimarySkills=%5Bobject%20Object%5D&SecondarySkills=%5Bobject%20Object%5D"
I tried lot to fix this. May i know where i am doing wrong? Thanks for your help.
You should use the relative path in your url instead of hard coding the entire folder structure, which is probably incorrect since you are getting a 404. And you need to change the url every time you publish the site to the hosting enviroment when you hard code it like that.
So change
var url = "http://sites/APPSTEST/JobRequisitionApp/Pages/AddNewItem.aspx?Title=...
into
var url = "/AddNewItem.aspx?Title=...
if both the pages are in the same folder. Should AddNewItem.aspx be located in the Pages folder, you have to add that folder of course: var url = "/Pages/AddNewItem.aspx?Title=...
I'm working on a project in which the user is sent to the directory name they entered in an input, like so:
function sendanswer(e) {
if (e.keyCode === 13) {
e.preventDefault();
var answer = document.answerarea.input.value;
if (answer) {window.location.href = answer;}
}
}
document.answerarea.input.onkeypress = sendanswer;
This works fine. But now I want for the user to be automatically redirected to the directory they specified every time they visit the page, BUT only if they didn't recieve a 404 error after navigating to the directory. I imagine this would be accomplished by erasing the cookie when the 404 page is visited.
But how would the redirecting-to-cookie process work?
When you get input from use set a cookie using this code:
function sendanswer(e) {
if (e.keyCode === 13) {
e.preventDefault();
var answer = document.answerarea.input.value;
if (answer) {
window.location.href = answer;
//SET COOKIE WITH NAME redirectPath
document.cookie="redirectPath="+ answer;
}
}
}
Now on your home page (the page which user gets on visiting your site) add following call on-page load:
window.onload=function(){
var kuki = "redirectPath=";//NAME OF COOKIE WE SET
var cookies = document.cookie.split(';');
for(var i=0;i < cookies.length;i++) {
var c = cookies[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(kuki) == 0){
var path = c.substring(kuki.length,c.length);
//MOVE USER TO STORED PATH
document.location.href=path;
}
}
}
A better approach will be to read cookie on server-side and redirect user to their favourite folder from there.
For more reference check this answer.
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!