Why chrome-extension doesn't change the images? - google-chrome

I am new to chrome-extension and currently studying it. Im reading http://talks.codegram.com/creating-basic-chrome-extensions#/basic_example_4 the css tweaks already works but not with the changing of image...
mainifest.json
{
"name": "TrollFaces",
"version" : "0.0.1",
"manifest_version" : 2,
"description": "Must turn Codegram team members pics into troll faces.",
"permissions": ["tabs", "http://*/*", "background"],
"browser_action": {"default_icon": "16x16.png","default_popup": "popup.html"},
"content_scripts": [
{
// Change 'matches' attribute to load content
// script only in pages you want to.
"js": ["jquery.min.js", "contentscript.js"],
"matches": ["http://*/*"],
"css": ["basics.css"]
}
]
}
contentscript.js
$(document).ready(function() {
// Trollface image must be at 'my_extension/images/trollface.jpg'.
var trollface = chrome.extension.getURL("images/trollface.jpeg");
$('#content article img').each(function(index, image){
$(image).attr('src', trollface);
});
});
using inspect element over the photo which is not displaying
<img alt="Txus" height="150" src="chrome-extension://fdigngaajlfopnpffgcapbdekkbicngb/images/trollface.jpeg" width="225">

In order for the image (or any resource) to be "usable in the context of a web page" you have to declare it as a web accessible resource in the relevant section of your manifest.json. E.g.:
In manifest.json:
...
"web_accessible_resources": [
"images/trollface.jpeg"
],
...

Related

iframe in chrome extension background page is always getting cancelled

I am not able to load an iframe on the background page of a chrome extension.
I've tried loading iframe separately on html page and its working so, I think this issue has something to do with chrome extension or browser property
for example, if I add this in my chrome extension background page
<iframe id="stackoverflow" src="https://www.stackoverflow.com"></iframe>
I am always getting canceled status
WebSocket connection to 'ws://localhost:35729/livereload' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
manifest.json:
{
"name": "__MSG_appName__",
"short_name": "ixigo",
"version": "3.1.24",
"manifest_version": 2,
"description": "__MSG_appDescription__",
"icons": {
"16": "images/16.png",
"48": "images/48.png",
"128": "images/128.png"
},
"default_locale": "en",
"background": {
"scripts": [
"scripts/chromereload.js",
"scripts/libs/jquery.min.js",
"scripts/src/config.js",
"scripts/src/track.js",
"scripts/src/userIntentHandler.js",
"scripts/src/background.js",
"scripts/src/OneSignal.js",
"scripts/src/notificationsHandler.js"
],
"persistent": true
},
"content_scripts": [
{
"matches": [
"http://*/*",
"https://*/*"
],
"js": [
"scripts/contentscript.js"
],
"all_frames": true
},
{
"matches": [
"*://www.irctc.co.in/*",
"*://*.ixigo.com/*"
],
"js": [
"scripts/src/irctcAutofill.js",
"scripts/src/irctcAutofillEventHandler.js"
],
"all_frames": false
},
{
"matches": [
"*://*.indianrail.gov.in/*",
"*://*.ixigo.com/*"
],
"js": [
"scripts/libs/jquery.min.js",
"scripts/src/train.js",
"scripts/src/trainAvailability.js",
"scripts/src/runningStatus.js"
],
"run_at": "document_end",
"all_frames": true
}
],
"chrome_url_overrides": {
"newtab": "ixitab.html"
},
"options_page": "options.html",
"options_ui": {
"chrome_style": true,
"page": "options.html"
},
"permissions": [
"tabs",
"http://*.indianrail.gov.in/*",
"*://*.ixigo.com/*",
"cookies",
"notifications",
"gcm",
"storage"
],
"web_accessible_resources": [
"images/*",
"fonts/*",
"styles/*"
],
"update_url": "http://clients2.google.com/service/update2/crx",
"content_security_policy": "script-src 'self' https://ssl.google-analytics.com https://api.bing.com/osjson.aspx object-src 'self'"
}
So it appears that Chrome "cancels" the loading of an iframe in a background page, presumably for security reasons. BUT it still processes correctly and can send and receive messages as you'd expect. I have a demo set up here that loads up an iframe in the background page, sends a message to it, and the iframe echos the message back.
Since the request is showing canceled, a third party library I'm using that happens to load up an iframe to try and get a new token, is failing and I'll need to reconfigure it to still hook in to the messaging even though it thinks that it didn't load properly.
You've never been able to access the DOM / window of an iframe directly through the background page, all events have to go through messages as a security precaution.
In addition, and perhaps more importantly to your actual issue, the error in connecting you are getting is to "localhost:35729/livereload", that address isn't defined in your manifest.json permission section and is likely being aborted by chrome due to that.
The code for posterity:
background.js
window.onload = function(){
var frame = document.createElement('iframe');
frame.src = 'https://crustyjew.github.io/ChromeExtensionBug/';
document.body.appendChild(frame);
window.addEventListener('message',function(e){
console.log("message received: " + JSON.stringify(e.data));
});
console.log('posting message to iframe');
frame.addEventListener('load',function(){
frame.contentWindow.postMessage("TestMessage","*");
});
};
manifest.json
{
"name": "BackgroundIframeBug",
"short_name": "BGIframeBug",
"version": "1.0.0",
"manifest_version": 2,
"background":{
"scripts":["background.js"]
},
"permissions":[
"<all_urls>"
]
}
echo page to load in iframe
index.js =>
window.onload=function(){
function receiveMessage(e){
console.log('received message');
var origin = event.origin || event.originalEvent.origin;
e.source.postMessage({'origin':origin,'message':e.data},"*");
}
window.addEventListener('message',receiveMessage);}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<script src="index.js"></script>
</body>
</html>
Looks like that server is down. I see the links you're referencing on NTES, but they don't actually go to a webpage right now. Try for yourself:
http://www.indianrail.gov.in/pnr_Enq.html
http://www.indianrail.gov.in/seat_Avail.html
http://www.indianrail.gov.in/
Additionally, if/when that portion of the site comes online, you would have clicked through a "disclosure page" that likely created a session state that follows you around while you're browsing. Attempting to iframe directly to the inside of such a walled garden would also create that ERR_CONNECTION_REFUSED warning. Which is what happened on this URL:
http://enquiry.indianrail.gov.in/ntes/
Its a common method meant to keep content from wandering. :)

Auto Refresh on load page failure

I'm trying to create an extension for chrome that auto refreshes the page when the page load is failed for any reason.
my manifest.json:
{ "browser_action" : { "default_icon" : "icon.png"
},
"description" : "Making your first Google Chrome extension.",
"icons" : { "128" : "icon.png" },
"name" : "Tutorialzine Extension",
"version" : "1.0",
"permissions": [
"webRequest",
"tabs",
"<all_urls>"
],
"content_scripts": [
{
"matches": ["<all_urls>","http://*/*","https://*/*","*://*/*"],
"js": ["myscript.js"],
"run_at": "document_end"
}
]
}
myscript.js :
chrome.webRequest.onErrorOccurred.addListener(function details){
chrome.tabs.reload(details.tabId);
}
What am I doing wrong? Thanks in advance!
Content scripts don't have access to most of chrome.* APIs. It's clearly stated in the docs:
However, content scripts have some limitations. They cannot:
- Use chrome.* APIs (except for parts of chrome.extension)
You should use a background page or event page instead.
Also chrome.webRequest.onErrorOccurred.addListener(function details) is not a valid JavaScript code. function keyword shouldn't be there. I believe you copied this code from docs, but in docs this type of pseudo-JavaScript is used only to describe function definition (what types of arguments it expects, what type of values does it return etc.).

To execute a function on the button click in chrome extension

In the above screenshot you will see a panel and there are three buttons namely hide, close and clear.
I want to perform a particular action on click of those buttons.
Can you please suggest me some approach to achieve it?
Actually the panel created below is nothing but a div container which I have appended to the body of the current webpage.
So I had tried with one approach to inject my own script in that particular webpage and perform a particular action on those button clicks.
But that didn't work for me.
Can you please suggest me some other approach?
This is my manifest file :-
{
"name": "Demo Extension",
"version": "1.0.0",
"manifest_version": 2,
"browser_action": {
"default_icon": "icon.png"
},
"background": {
"scripts": ["jquery-1.7.2.js","code.js"]
},
"content_scripts": [
{
"matches": ["*://*/*"],
"js": ["jquery-1.7.2.js","content.js"],
"css": ["panel.css"],
"run_at": "document_end"
}
],
"permissions": [
"webRequest",
"tabs",
"http://*/*",
"https://*/*",
]
}
And my content.js file is as follows:
var data_div = $("<div class='panel'></div>");
data_div.css("position","fixed");
data_div.css("bottom","0px");
data_div.css("height","300px");
data_div.css("display","block");
data_div.css("width","100%");
data_div.css("overflow","scroll");
data_div.css("z-index","1004");
data_div.css("background-color","#C0C0C0");
$("body").append(data_div);
data_div.html("One big data set here");

Chromium extension: javascript not executed

Making a simple plugin , which executes javascript when a page is loaded , and I want to execute different javascript on different page
But the following code wasn't working as expected , no "alert" was triggered:
background.html:
<html><body>
<script>
chrome.webRequest.onCompleted.addListener(
function(details) {
alert (details.url);
},
{
urls: ["*"],
types: ["main_frame"]
},
[]
);
</script>
</body></html>
manifest.json:
{
"name": "JS",
"background_page": "background.html",
"permissions": [
"webRequest",
"*"
],
"version":"0.10"
}
Alerts and console.log made from the background page of an extension simply aren't visible on the general pages.
If you want to see them, you have to open the background page : Go to the extensions settings page (menu tools/extensions) and click the "background.html" link below the name of your extension.
In your case it may be better, during development phase, to simply add the console.log and alerts in the content scripts (i.e. not the background page). So you can read them without opening the background page.
EDIT : as requested, an extension that will simply alert the location :
main.js :
alert(document.location.href);
manifest.json :
{
"name": "Any name",
"version": "3.3",
"background_page": "background.html",
"content_scripts": [
{
"matches": ["http://*/*"],
"all_frames" : true,
"run_at" : "document_end",
"js": [
"main.js"
]
}
]
}
Yes I tested it. And yes it's as painful as it sounds. You should use console.log instead of alert during your dev.

Chrome extension causes problems with jquery and javascript on some pages

I have a small chrome extension which I want to use to change text. It works just the way I want it to(clicking the icon changes text), but on some pages the existing jquery stops working when the app is enabled. What am I doing wrong?
Files: manifest.json, myscript.js and background.html
manifest.json content:
{
"name": "My extension",
"version": "1.0",
"background_page": "background.html",
"permissions": [
"tabs", "http://*/*"
],
"content_scripts": [
{
"matches": ["http://*/*"],
"matches": ["https://*/*"],
"js": ["myscript.js"]
}
],
"browser_action": {
"default_icon": "icon.png"
}
}
myscript.js content:
var array = {"not":" NOT ", "like":" LIKE ", "job":"JOBS"}
for (var val in array)
document.body.innerHTML = document.body.innerHTML.replace(new RegExp(val, "g"), array[val]);
background.html content:
<script>
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null,
{file:"myscript.js"});
});
</script>
document.body.innerHTML is very bad.
When you use it, you're treating DOM nodes as raw text. Those DOM nodes have event handlers and even a simple document.body.innerHTML+='...' will send the existing nodes to oblivion, creating new ones, without event handlers.
So instead, you need to iterate through all the text nodes in the document (*see here how) and do an innerHTML each one individually.
Sănătate!