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.
Related
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. :)
I'm novice in Google Chrome Extension development and I'm running through an issue which is causing the content script not getting executed. Below is a detailed description of the issue.
I'm working an extension to read some DOM content from a web site per say example.com I've the following files and the respective code part of it.
manifest
{
"manifest_version" : 2,
"name" : "My First Chrome App",
"description" : "My First Chrome App",
"version": "1.0",
"browser_action" : {
"default_title" : "Hello"
},
"permissions" : ["tabs"],
"background" : {
"scripts" : ["background.js"],
"persistence" : false
},
"content_scripts":[
{
"matches": [
"http://example.com/HomePage.aspx"
],
"js": ["jquery_224.js", "content_script.js"]
}]
}
background.js
My intention is to create a tab and surf to a page which is mentioned in the below script. And, it has to send a message to content_script.js
chrome.browserAction.onClicked.addListener(function(){
chrome.tabs.create({ url: "http://example.com/HomePage.aspx" }, function(tab){
chrome.runtime.sendMessage({authKey : "parse-dom"});
setTimeout(function(){
chrome.tabs.remove(tab.id);
}, 2000);
});
});.
content_script.js
Here I'm trying to read the authKey that I'm sending it from my background.js
chrome.runtime.onMessage.addListener(function(request,sender,response){
alert(request.authKey);
});
Unfortunately, I'm not getting the alert nor seeing any script errors. I have gone through the Chrome Messaging API and followed the same
Where am I going wrong?
Try with
"content_scripts":[
{
"run_at": "document_start",
More infos: https://developer.chrome.com/extensions/content_scripts
or try putting a timeout on your background sendMessage
EDIT: I've also noticed on manifest.json you have an HTTPS match while you are creating a tab with an HTTP address
So I'm in the midst of creating my first Chrome Extension (Trying)
I feel like I'm close... But I genuinely don't know what to google to get the answers I need. So I'm sorry if this is a silly question.
Essentially what I'm trying to do is on click of extension - Append HTML & CSS to body and run a jQuery function. But from the looks of it, I need to call in jQuery in the manifest? Which I think I've done and it's still not working.
My Code:
manifest.json
{
"name": "Title",
"description": "Description",
"version": "1.0",
"browser_action": {
"default_title": "Hover Title",
"default_icon": "icon.png"
},
"content_scripts": [ {
"js": [ "jquery-1.7.2.min.js", "background.js" ],
"matches": [ "http://*/*", "https://*/*"]
}],
"manifest_version": 2
}
background.js
chrome.browserAction.onClicked.addListener(function(tab) {
(function ($) {
$('body').append("Hello");
alert("Hello");
console.log("Hello");
}(jQuery));
});
Any insight into where I'm going wrong would be massively helpful!
Thank you!!
Chrome extension architecture is simple but it doesn't mean one can write code without studying it.
There are two methods of injecting content scripts:
Unconditionally on all specified urls, in which case "content_script" key is used in the manifest and the content scripts communicate with the background page via runtime.sendMessage.
Only when some event occurs like e.g. the user clicks our toolbar icon, in which case we only need the permission to access the active tab.
So in the given case we'll attach the icon click handler and inject the code afterwards:
manifest.json:
{
"name": "Title",
"description": "Description",
"version": "1.0",
"browser_action": {
"default_title": "Icon Title",
"default_icon": "icon.png"
},
"background": {
"scripts": ["background.js"]
},
"permissions": ["activeTab"],
"manifest_version": 2
}
background.js (this is an event page because we didn't use "persistent": true in the manifest, so be advised that the [global] variables will be lost after a few seconds of inactivity; instead you should use chrome.storage API or HTML5 localStorage/sessionStorage/and so on):
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript({file: "jquery-1.7.2.min.js"}, function(result) {
chrome.tabs.executeScript({file: "content.js"}, function(result) {
});
});
});
content.js (the code runs in a sandbox so there's no need to hide global variables using IIFE)
$('body').append("Hello");
alert("Hello");
console.log("Hello");
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"
],
...
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.).