Chrome extension: intercept HTTP Response - javascript

I saw many pages talking about how to intercept the HTTP Response from a site. I'm trying this: Chrome Extension - How to get HTTP Response Body?
There are no execuble programs... this is my code:
manifest.json:
{
"manifest_version": 2,
"name": "Extension Name",
"description": "Some Desc.",
"version": "1.1",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "index.html"
},
"permissions": [
"activeTab",
"storage",
"tabs",
"https://*.google.com/"
],
"content_scripts": [
{
"matches": ["https://*.google.com/"],
"run_at": "document_start",
"js": ["contentscript.js", "inject.js"]
}
],
"web_accessible_resources": ["injected.js"]
}
index.html:
<html>
<head>
<script src="contentscript.js"></script>
</head>
<body>
<p>HTTP INTERCEPTOR</p>
</body>
</html>
injected.js:
(function(xhr) {
console.log('injeced file');
var XHR = XMLHttpRequest.prototype;
var open = XHR.open;
var send = XHR.send;
var setRequestHeader = XHR.setRequestHeader;
XHR.open = function(method, url) {
this._method = method;
this._url = url;
this._requestHeaders = {};
this._startTime = (new Date()).toISOString();
return open.apply(this, arguments);
};
XHR.setRequestHeader = function(header, value) {
this._requestHeaders[header] = value;
return setRequestHeader.apply(this, arguments);
};
XHR.send = function(postData) {
this.addEventListener('load', function() {
var endTime = (new Date()).toISOString();
var myUrl = this._url ? this._url.toLowerCase() : this._url;
if(myUrl) {
if (postData) {
if (typeof postData === 'string') {
try {
// here you get the REQUEST HEADERS, in JSON format, so you can also use JSON.parse
this._requestHeaders = postData;
} catch(err) {
console.log('Request Header JSON decode failed, transfer_encoding field could be base64');
console.log(err);
}
} else if (typeof postData === 'object' || typeof postData === 'array' || typeof postData === 'number' || typeof postData === 'boolean') {
// do something if you need
}
}
// here you get the RESPONSE HEADERS
var responseHeaders = this.getAllResponseHeaders();
if ( this.responseType != 'blob' && this.responseText) {
// responseText is string or null
try {
// here you get RESPONSE TEXT (BODY), in JSON format, so you can use JSON.parse
var arr = this.responseText;
// printing url, request headers, response headers, response body, to console
console.log(this._url);
console.log(JSON.parse(this._requestHeaders));
console.log(responseHeaders);
console.log(JSON.parse(arr));
} catch(err) {
console.log("Error in responseType try catch");
console.log(err);
}
}
}
});
return send.apply(this, arguments);
};
})(XMLHttpRequest);
inject.js I set a timeout so I can enable the debugger:
/**
* code in inject.js
* added "web_accessible_resources": ["injected.js"] to manifest.json
*/
setTimeout(function() {
var s = document.createElement('script');
s.src = chrome.extension.getURL('injected.js');
s.onload = function() {
this.remove();
console.log('remove');
};
(document.head || document.documentElement).appendChild(s);
}, 10000);
Why the code is not injected into https://www.google.com/? Inspecting the DOM I don't see the code... the code runs and xhr is started but the methods open, setRequestHeader and send are never called.

The code is from my answer here.
Content Script, in that case, is used to communicate with injected.js.
Sample code is as follows:
/**
* Content script currently only used to communicate extension state on off message to injected.js
* Sends back response to extension (popup.js) after sending message to injected.js
*/
$(function(){
// localStorage is different from chrome.storage
// localStorage for injected script, and chrome.storage for extension script (popup.js) and contentscript.js
chrome.storage.sync.get("state", function (data) {
if (typeof data.state === 'undefined') {
chrome.storage.sync.set({"state": "on"}, function() {}); // async
}
console.log("Content Script State: " + data.state);
});
// message from extension script to this content script.
// will be used to receive enable disable messages
// sends response in 'status' variable
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"content script receiving message from a content script:" + sender.tab.url :
"content script receiving message from the extension");
if (request.toggle === true) {
chrome.storage.sync.set({"state": "on"}, function() { console.log("Content Script State Updated: on"); }); // async
var data = {
app_state: "on"
};
document.dispatchEvent(new CustomEvent("app_state_message", {detail: data}));
// cannot return state in function since above .set is async and popup.js does not receive the response
sendResponse({state: "on"});
} else if (request.toggle === false) {
chrome.storage.sync.set({"state": "off"}, function() { console.log("Content Script State Updated: off"); }); // async
var data = {
app_state: "off"
};
document.dispatchEvent(new CustomEvent("app_state_message", {detail: data}));
sendResponse({state: "off"});
} else {
sendResponse({state: "error"});
}
});
});
Please read more on Content Scripts. Hope you find this useful.

Related

JavaScript & Chrome Extensions: Pass Variable with Custom Events

manifest.json
{
"name": "Omegle IP",
"version": "0.5",
"options_page": "options.html",
"options_ui": {
"page": "options.html",
"open_in_tab": false
},
"background": {
"scripts": ["background.js"],
"persistent": true
},
"manifest_version": 2,
"description": "Become a Hacker; You see the IP in the chat window",
"permissions": ["tabs", "https://*.omegle.com/*", "storage"],
"web_accessible_resources": ["inject.js"],
"content_scripts" : [{
"matches" : ["https://*.omegle.com/*"],
"run_at": "document_end",
"js" : ["contentscript.js"]
}],
"icons": {
"16": "16.png",
"32": "32.png",
"48": "48.png",
"128": "128.png"
}
}
contentscript.js
var s = document.createElement('script');
// TODO: add "script.js" to web_accessible_resources in manifest.json
s.src = chrome.runtime.getURL('inject.js');
s.onload = function() {
this.remove();
};
(document.head || document.documentElement).appendChild(s);
inject.js
chrome.storage.sync.get(['tracker', 'api'], function (obj) {
tracker = obj.tracker;
api = obj.api;
getIp(tracker, api);
});
function getIp(tracker, api){
console.log(tracker + api)
}
I cant access chrome.storage.sync.get from inject.js. But I need to... Is there a way to put the chrome request to the contentscript and pass the variables to inject.js
contentscript.js basically just creates a script field and puts the inject.js into it.
the inject.js file is normally larger, but you dont need all of that
There is a post "https://stackoverflow.com/questions/9515704/use-a-content-script-to-access-the-page-context-variables-and-functions" how to implement this, i tried but i didnt achieve to get it to work...
Could you please provide a working method, to get it to work?
Update:
contentscript.js
chrome.storage.sync.get(['tracker'], function (obj) {
tracker = obj.tracker;
ChromeExtensionData(tracker);
});
function ChromeExtensionData(tracker) {
var data = {
tracker: tracker,
};
console.log("Sending:", tracker); // works
console.log(document.dispatchEvent(new CustomEvent('ChromeExtensionData', { detail: data }))); // true
}
inject.js
document.addEventListener('ChromeExtensionData', function (e) {
var tracker = e.detail;
console.log('received', tracker);
});
getIp(tracker); // tracker is not definied
Its in the comments whats wrong. And i really dont know why
Update:
inject.js
document.addEventListener('ChromeExtensionData', function (e) {
console.log("Recieved"); // test -> doesnt work
var tracker = e.detail;
console.log('received', tracker); // doenst log anything
getIp(tracker);
});
contentscript.js
var s = document.createElement('script');
// TODO: add "script.js" to web_accessible_resources in manifest.json
s.src = chrome.runtime.getURL('inject.js');
s.onload = function() {
this.remove();
};
(document.head || document.documentElement).appendChild(s);
chrome.storage.sync.get(['tracker'], function (obj) {
tracker = obj.tracker;
ChromeExtensionData(tracker);
});
function ChromeExtensionData(tracker) {
jsontracker = JSON.stringify(tracker);
var data = {
tracker: jsontracker
};
console.log("Sending:", tracker); // works
document.dispatchEvent(new CustomEvent('ChromeExtensionData', { detail: data }));
}
Working Answer
inject.js
document.addEventListener('ChromeExtensionData', function (e) { // waits for variable from contentscript
var data = e.detail;
tracker = data.tracker;
trollChecked = data.trollChecked;
getIp(tracker, trollChecked);
});
contentscript.js
var s = document.createElement('script');
s.src = chrome.runtime.getURL('inject.js');
s.onload = function() {
this.remove();
chrome.storage.sync.get(['tracker', 'troll'], function (obj) {
tracker = obj.tracker;
trollChecked = obj.troll
var data = {
tracker: tracker,
trollChecked: trollChecked
};
document.dispatchEvent(new CustomEvent('ChromeExtensionData', { detail: data })); // gets variable from optionspage and sends to the script
});
};
(document.head || document.documentElement).appendChild(s);
You can learn how to set chrome variables from here
Big Shoutout to wOxxOm for helping me and making this result possible

Access user options in background.js in Chrome Extension

I'm trying to access chrome.storage.sync where I store some user options in my background.js but the asynchronous nature of chrome.storage.sync.get is causing me issues.
If I try and use chrome.storage.sync.get within my chrome.webRequest.onBeforeRequest.addListener the callback isn't quick enough for the function to use it.
I have tried adding the user options as a global variable within background.js but it appears to me that that value doesn't persist.
Anyone else using user options in background.js?
function getoption(){
chrome.storage.sync.get({
radarpref: 'nothing',
}, function(items) {
console.log(items.radarpref);
return items.radarpref;
});
}
var hold = getoption();
console.log (hold) //this returns hold value
chrome.webRequest.onBeforeRequest.addListener(
function(info) {
//this doesn't work - yet
console.log('i dont see the hold');
console.log(hold) //hold not returned when callback ran
...
If you need to synchronously use settings from any async storage - the best way to do it is to cache it.
You need to load the settings to the cache on background.js start and then you need to update cache each time chrome.storage.onChanged event triggered.
Example how to do it:
manifest.js
{
"manifest_version": 2,
"name": "Settings Online demo",
"description": "Settings Online demo",
"applications": {
"gecko": {
"id": "852a5a44289192c3cd3d71e06fdcdb43b1437971#j2me.ws"
}
},
"version": "0.0.1",
"background": {
"scripts": ["background.js"]
},
"permissions": [
"storage",
"webRequest",
"webRequestBlocking",
"<all_urls>"
],
"options_ui": {
"page":"properties.html",
"chrome_style": true
}
}
Note that you need to have non-temporary application id if you need to work it on firefox, <all_urls> permission is needed to get access to any url request processing.
background.js
((storage) => {
let settings = (function(properties) {
// Save settings
this.set = (properties,ok) => {
for(key in properties || {}){
this[key]=properties[key];
}
storage.set(
properties
,() => {
ok(settings);
});
};
//Default values processing
for(key in properties || {}){
this[key]=properties[key];
}
// Initial settings read
storage.get(properties,(properties) => {
for(key in properties){
this[key]=properties[key];
}
});
// Listen settings change and cache it
chrome.storage.onChanged.addListener((msg) => {
for(key in msg){
this[key]=msg[key].newValue;
}
});
return this;
}).call({},{"property":"default","name":"me"})
chrome.webRequest.onBeforeRequest.addListener(
function(info) {
// Update and persist settings
settings.set({"lastRequest":info},()=>{console.log("Settings saved")});
console.log('Catch', settings.name,settings.property);
},{urls:["https://*/*"]});
})(chrome.storage.sync || chrome.storage.local);
Note that I use chrome.storage.sync || chrome.storage.local because some browsers (Opera, mobile browsers) do not support sync-storage, but support local storage.
And the property page to see how can property changes are processing:
properties.html
<html>
<head>
<script src="properties.js" type="text/javascript"></script>
</head>
<body>
<label>Property:<input id="property" type="text"></label>
<input id="save-properties" value="save" type="submit">
</body>
</html>
properties.js
((storage) => {
let saveOptions = () => {
let property = document.getElementById("property").value;
storage.set({
"property": property
},() => {
window.close();
});
}
let restoreOptions = () => {
storage.get({
"property": "default"
}, (properties) => {
document.getElementById("property").value = properties.property;
});
document.getElementById("save-properties").addEventListener("click", saveOptions);
}
document.addEventListener("DOMContentLoaded", restoreOptions);
})(chrome.storage.sync || chrome.storage.local);
That's all :)
P.S> This solution has a weak point: if your app is settings-sensitive and can't work with default settings, or you need to be sure that you're using custom settings on start - you need to delay background.js start while settings are not loaded. You may to it with callback or with promise:
background.js - wait while settings will be loaded with callback
((storage) => {
let settings = (function(properties) {
// Update settings
this.set = (properties,ok) => {
for(key in properties || {}){
this[key]=properties[key];
}
storage.set(
properties
,() => {
ok(settings);
});
};
//Default values processing
for(key in properties || {}){
this[key]=properties[key];
}
// Listen settings change and cache it
chrome.storage.onChanged.addListener((msg) => {
for(key in msg){
this[key]=msg[key].newValue;
}
});
// Initial settings read
storage.get(properties,(properties) => {
for(key in properties){
this[key]=properties[key];
}
mainLoop();
});
return this;
}).call({},{"property":"default","name":"me"})
let mainLoop = () => {
//.. all you settings-sensitive code
chrome.webRequest.onBeforeRequest.addListener(
function(info) {
// Update settings and persist it
settings.set({"lastRequest":info},()=>{console.log("Settings saved")});
console.log('Catch', settings.name,settings.property);
},{urls:["https://*/*"]});
};
})(chrome.storage.sync || chrome.storage.local);
background.js - wait while settings will be loaded with promise
((storage) => {
let settings = ((properties) => {
this.set = (properties) => {
for(key in properties || {}){
this[key]=properties[key];
}
return new Promise((ok,err) => {
storage.set(
properties
,() => {
ok(settings);
});
});
};
return new Promise((ok,err) => {
//Default values processing
for(key in properties || {}){
this[key]=properties[key];
}
// Listen settings change and cache it
chrome.storage.onChanged.addListener((msg) => {
for(key in msg){
this[key]=msg[key].newValue;
}
});
// Initial settings read
storage.get(properties,(properties) => {
for(key in properties){
this[key]=properties[key];
}
ok(this);
});
});
}).call({},{"property":"default","name":"me"}).then((settings) => {
//.. all you settings-sensitive code
chrome.webRequest.onBeforeRequest.addListener(
function(info) {
// Update settings and persist it
settings.set({"lastRequest":info}).then(()=>{console.log("Settings saved")});
console.log('Catch', settings.name,settings.property);
},{urls:["https://*/*"]});
}).catch(()=>{});
})(chrome.storage.sync || chrome.storage.local);
Read more
Storage specs/firefox:
https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/storage
Storage spect/chrome: https://developer.chrome.com/apps/storage
Permission requests/firefox:
https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Request_the_right_permissions

chrome.runtime.connectNative from external url

I have a Google Chrome extension which contains the following two files...
manifest.json
{
"key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDcBHwzDvyBQ6bDppkIs9MP4ksKqCMyXQ/A52JivHZKh4YO/9vJsT3oaYhSpDCE9RPocOEQvwsHsFReW2nUEc6OLLyoCFFxIb7KkLGsmfakkut/fFdNJYh0xOTbSN8YvLWcqph09XAY2Y/f0AL7vfO1cuCqtkMt8hFrBGWxDdf9CQIDAQAB",
"name": "Native Messaging Example",
"version": "1.0",
"manifest_version": 2,
"description": "Send a message to a native application.",
"app": {
"launch": {
"local_path": "index.html"
}
},
"icons": {
"128": "icon-128.png"
},
"permissions": [
"nativeMessaging"
],
"externally_connectable": {
"matches": ["*://*.chrome-extension.com/*"]
},
"background": {
"scripts": ["background.js"]
}
}
background.js
var sendResponseCallBack;
chrome.runtime.onMessageExternal.addListener(
function(request, sender, sendResponse) {
sendResponseCallBack = sendResponse;
var message = {"comment": '*** ' + request['comment'] + ' ***'};
var useNative = false;
if (useNative) {
connect();
sendNativeMessage(message);
}
else {
sendResponseCallBack(message);
}
}
);
function connect() {
var hostName = "com.google.chrome.example.echo";
port = chrome.runtime.connectNative(hostName);
port.onMessage.addListener(onNativeMessage);
port.onDisconnect.addListener(onDisconnected);
}
function sendNativeMessage(message) {
port.postMessage(message);
}
function onNativeMessage(message) {
port.disconnect();
sendResponseCallBack(message);
}
I also configured the virtual host: chrome-extension.com to access to the url from a local server:
http://www.chrome-extension.com/
With the Chrome extension installed and enabled, if I access to:
http://www.chrome-extension.com/
and the variable useNative = false then I get a response from the plugin through: sendResponseCallBack(message);, but if useNative = true then I don't get any response from the plugin, I get: undefined and also the native operation which should take about 5 seconds, doesn't go thru because the undefined response is returned in 0 seconds.
I also have enabled another html page I access thru the extension url:
chrome-extension://knldjmfmopnpolahpmmgbagdohdnhkik/calc-with-os.html
Inside that page I include the calc-with-os.js file which contains the above functions: connect() sendNativeMessage(message) onNativeMessage(message) and the function: chrome.runtime.connectNative works properly performing the native process in all its phases.
Any idea on how can I connect to a native process from an external url?
[EDIT: TRY NUMBER 2]
Based on the comment of: #wOxxOm I did the following modification to the code with the purpose of don't send the message to fast and wait for the native process to start, but it is not still working.
Any other suggestions?
var port = null;
var sendResponseCallBack;
chrome.runtime.onMessageExternal.addListener(
function(request, sender, sendResponse) {
sendResponseCallBack = sendResponse;
connect(request);
}
);
function connect(request) {
chrome.runtime.onConnect.addListener(function(p){
port = p;
port.onMessage.addListener(onNativeMessage);
port.onDisconnect.addListener(onDisconnected);
var message = {"comment": '*** ' + request['comment'] + ' ***'};
sendNativeMessage(message);
});
var hostName = "com.google.chrome.example.echo";
chrome.runtime.connectNative(hostName);
}
function sendNativeMessage(message) {
port.postMessage(message);
}
function onNativeMessage(message) {
port.disconnect();
sendResponseCallBack(message);
}

Tab Listener not Getting Activated by Message from Background Script

I am sending a message to the tab were I have a content script (getTradingData.js) from the background.js with the following code:
alert("Automated TradingView Extension is running");
chrome.tabs.query({
url: 'https://www.tradingview.com/*'
}, function(tabs) {
if (tabs.length == 1) {
chrome.tabs.sendMessage(tabs[0].id, {subject: "testConnection"}, function(response) {
alert(response); //THIS RETURNS UNDEFINED
if (response.msg == "getTradingDataScriptHere") {
alert("Script Already Injected. Do not reinject"); //THIS IS NOT RUNNING
} else {
chrome.tabs.executeScript(tabs[0].id, {file: "jquery-2.2.3.min.js"});
chrome.tabs.executeScript(tabs[0].id, {file: "jquery.waituntilexists.min.js"});
chrome.tabs.executeScript(tabs[0].id, {file: "getTradingData.js"});
alert("Injected all Nessessary Scripts for Auto Trading View to work"); //THIS IS NOT RUNNING
}
});
} else {
alert("Please have one and only one tradingview chart page opened.");
}
});
var price = "Waiting For Price"
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.subject == "getPrice") {
sendResponse({
price: price
});
} else if (request.from == "getTradingData" && request.subject == "scriptLoaded") {
//getTradingData.js Script has Fully Loaded onto Website
} else if (request.from == "getTradingData" && request.subject == "updatePrice") {
price = request.price
}
});
However the response return as undefined. So basically I am not getting a response back.
Here is what I have in my getTradingData.js that should respond to the message:
alert("getTradingData.js is Running");
//Send message to let the extension know the script has been injected on site
chrome.runtime.sendMessage({
from: 'getTradingData',
subject: 'scriptLoaded'
});
chrome.runtime.onConnect.addListener(function(port) { //THIS DOESN'T WORK EITHER
console.assert(port.name == "tradingdata");
port.onMessage.addListener(function(request) {
if (request.msg == "Knock knock")
port.postMessage({subject: "price"});
else if (msg.answer == "Madame")
port.postMessage({question: "Madame who?"});
else if (msg.answer == "Madame... Bovary")
port.postMessage({question: "I don't get it."});
});
});
//to check if script already injected
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
alert("got message"); //THIS IS NOT RUNNING
if (request.subject == "testConnection") {
sendResponse({msg: "getTradingDataScriptHere"});
}
});
//wait till item has loaded
$(".dl-header-figures").waitUntilExists(function(){
alert($(".dl-header-figures").text());
updatePrice();
});
function updatePrice(){
alert("updating price");
chrome.runtime.sendMessage({
from: 'getTradingData',
subject: 'updatePrice',
price: $(".dl-header-figures").text()
});
}
//TODO: Use long lived connections for this to work: https://developer.chrome.com/extensions/messaging
// setInterval(updatePrice(), 3000);
However this never gets activated, I never get the alert "got message".
Here is what my manifest.json looks like:
{
"manifest_version": 2,
"name": "Automated TradingView Strategy",
"description": "This extension shows a Google Image search result for the current page",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"background": {
"scripts": ["jquery-2.2.3.min.js", "background.js"]
},
"content_scripts": [
{
"matches": ["https://www.tradingview.com/chart/*", "http://www.tradingview.com/*"],
"js": ["jquery-2.2.3.min.js", "jquery.waituntilexists.min.js", "getTradingData.js"]
}
],
"permissions": [
"activeTab",
"tabs",
"*://*.tradingview.com/*",
"https://ajax.googleapis.com/"
]
}
What am I doing wrong? How can I make it send a response back. Even when I refresh extension which should reload background.js without reloading tabs which already has the content script injected in it I get no response because the Listener is not activated.
What are you trying to do exactly in your background script?
chrome.tabs.query runs only once when you load the extension, also, the scripts you are injecting with chrome.tabs.executeScript should be injected already because of the manifest.
I don't know exactly what you're trying to do, but, you can listen to an event every time a tab is updated (tabs are updated after being created) - chrome.tabs.onUpdated.addListener
Updated background.js:
alert("Automated TradingView Extension is running");
chrome.tabs.query({
url: 'https://www.tradingview.com/*'
}, function(tabs) {
console.log(tabs);
if (tabs.length == 1) {
chrome.tabs.sendMessage(tabs[0].id, {subject: "testConnection"}, function(response) {
if (response) {
alert("Script Already Injected. Do not reinject");
} else {
chrome.tabs.executeScript(tabs[0].id, {file: "jquery-2.2.3.min.js"});
chrome.tabs.executeScript(tabs[0].id, {file: "jquery.waituntilexists.min.js"});
chrome.tabs.executeScript(tabs[0].id, {file: "getTradingData.js"});
alert("Injected all Nessessary Scripts for Auto Trading View to work");
}
});
} else {
alert("Please have one and only one tradingview chart page opened.");
}
});
var price = "Waiting For Price"
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.subject == "getPrice") {
sendResponse({
price: price
});
} else if (request.from == "getTradingData" && request.subject == "scriptLoaded") {
//getTradingData.js Script has Fully Loaded onto Website
} else if (request.from == "getTradingData" && request.subject == "updatePrice") {
price = request.price
}
});

Chrome Extension: CRX file not working properly

I am trying to install my Extension's CRX version but it is not loading some of image files on extension button placed on address bar.I have even put try/catch but it is not giving any error either. The Developer/Unpack version is working just fine.
What's wrong am I doing? What I guess my all image files are not compressed in CRX file. Unfortunately I can't extract CRX content either as renamig to .ZIP is not letting me to unzip on MacoSX
I am installing CRX by dragging on to extensions page.
How do I test the issue?
Code is given below:
Manifest.jsonn
{
"name": "Domain Colors",
"version": "1.0",
"manifest_version": 2,
"description": "Change Button Color for domains.",
"content_scripts": [
{
"matches": ["http://*/*","https://*/*"],
"js": ["script.js"]
}
],
"permissions": [
"tabs", "http://*/*"
],
"browser_action": {
"default_title": "Colry",
"default_icon": "blue.png"
},
"background": {
"scripts": ["background41.js"]
}
}
script.js
alert("Testing Version..Wait for a while");
var request = new XMLHttpRequest();
if (request == null)
{
alert("Unable to create request");
}
else
{
try
{
var timestamp = new Date().getTime(); //to avoid cache ajax calls
var randomnumber=Math.floor(Math.random()*11);
timestamp = timestamp * randomnumber;
var _domain = document.domain;
_domain = _domain.replace("www.","");
var url = "http://xxxxnet/xxx/xxx.asp?xx="+_domain+"&ts="+timestamp;
request.onreadystatechange = function()
{
//request.setRequestHeader('Cache-Control', 'no-cache');
//request.setRequestHeader('Pragma', 'no-cache');
if(request.readyState == 4)
{
LDResponse(request.responseText);
}
}
request.open("GET", url, true);
request.send(null);
}
catch(e){
alert('An error has occurred in AJAX Call: '+e.message)
}
}
function LDResponse(response)
{
var json = JSON.parse(response);
alert(response);
var msg = document.domain+","+json["buttonColour"]+","+json["buttonTip"];
chrome.extension.sendMessage(msg);
}
background file
var currentUrl = "";
var currentColor = "";
var currentTip = "";
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo) {
if (changeInfo.status === 'loading')
{
chrome.browserAction.setIcon({
path:'chrome-extension://lkhgldilknhpmdodeblhnbniahbjcdcm/gray.png',
tabId:tabId
});
chrome.extension.onMessage.addListener(function(message, sender)
{
try
{
var stuff = message.split(",");
currentUrl = stuff[0];
currentUrl = currentUrl.replace("www.","");
currentColor = stuff[1];
currentTip = stuff[2];
}
catch(e)
{
alert('An error in onMessage method: '+e.message)
}
});
}
else if (changeInfo.status === 'complete')
{
try
{
chrome.browserAction.setIcon({
path:'chrome-extension://lkhgldilknhpmdodeblhnbniahbjcdcm/'+currentColor+".png",
tabId:tabId
});
chrome.browserAction.setTitle({
tabId:tabId,
title:currentTip
});
}
catch(e)
{
alert('An error in Complete method: '+e.message)
}
}
});
Thanks
Replace path:'chrome-extension://lkhgldilknhpmdodeblhnbniahbjcdcm/'+currentColor+".png with path: chrome.extension.getURL("currentColor.png") to get it to work.
Your runtime extension id is not lkhgldilknhpmdodeblhnbniahbjcdcm, so to use dynamic generated content you should use chrome.extension.getURL()

Categories

Resources