Chrome extension inject js - javascript

I want to create a new chrome extension but it don't work.
I want to inject a js file into web page (all web page,not only one.If i push the chrome icon on google the script must execute,if i push the icon on facebook it must execute ect.)
this is background.js
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript({
null,{file: "backgrounds.js"} });
});
this is backgrounds.js
document.body.innerHTML="display div elem with style and id";
this is manifest.json
{
"name": "MyExt",
"description": "an extension,what else?",
"version": "1.0",
"permissions": [
"activeTab"
],
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["background.js"]
}
],
"browser_action": {
"default_title": "myExt"
},
"manifest_version": 2
}
what i wrong?
I'm on windows 8.1 Update 1 with chrome last version

Your manifest is wrong: you should set background.js as your background script:
"background" : { "scripts" : [ "background.js" ] },
and remove the "content_scripts" section.
The "activeTab" permission means that you don't need to specify host permissions to inject in the current tab upon browser action click, so no other permissions are needed.
The tabId argument is optional, you can just drop it instead of passing null. And your invocation is wrong (you're wrapping two arguments in a single object). Here's the correct way:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript({file: "backgrounds.js"});
});

Related

How to run background.js only on specific links?

I'm trying to write a chrome extension that closes tabs when they're loaded if their links contain specific words / strings. My intention was to solve that using the matches statement in the manifest.json. Unfortuantely this doesn't work. My manifest.json looks like this:
{
"manifest_version": 2,
"name": "Chrome Extension",
"version": "0.1",
"permissions": [
"tabs"
],
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["content.js"]
}
],
"background": {
"matches": [
"https://www.google.de/",
"https://sghm.eu/iserv/login"
],
"scripts": ["background.js"],
"persistent": true
}
}
And my background.js like this:
chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
console.log('background running');
chrome.tabs.remove(tabId, function() { });
}
})
In my opinion I've expressed clearly that the script only runs on google and sghm.eu, so why does it run on every loaded page?
Problems:
The "background" section can't have "matches" as you can see in the documentation. The background script runs in a separate hidden background page that's not related to tabs.
The content script declared in your manifest.json runs on all URLs. For the task you want to achieve you don't need a content script at all.
Solution consists of several steps:
Remove "content_scripts" section
Remove "matches" from "background" section
Switch to an event page script by specifying "persistent": false
Add "webNavigation" permission in manifest.json and use it to detect URL navigation.
background.js:
chrome.webNavigation.onCompleted.addListener(closeTab, {
url: [
{urlPrefix: 'https://www.google.de/'},
{urlPrefix: 'https://sghm.eu/iserv/login'},
]
});
function closeTab(e) {
if (!e.frameId) {
chrome.tabs.remove(e.tabId);
}
}

Defining a hotkey in Google documents using Chrome extension

I am trying to define a new hotkey in Google documents. I am trying to use a Chrome extension, the problem is when the document area is active, the browser can't listen to the event fired. Here's the extension code.
Edit: Here's the manifest file
{
"manifest_version": 2,
"name": "My Cool Extension",
"version": "0.1",
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["jquery-3.2.1.js", "content.js"]
}
],
"permissions": [
"tabs"
]
}
Here's the content.js file
var map = {17: false};
$('body').keydown(function(e) {
if (e.keyCode in map) {
map[e.keyCode] = true;
if (map[17]) {
console.log("Hi");
}
}
}).keyup(function(e) {
if (e.keyCode in map) {
map[e.keyCode] = false;
}
});
The above extension works fine on any website. When you press ctrl, it will log "Hi". The extension works fine on any website and in Google Docs itself if the upper bar that contains the menus is active. It logs Hi when the ctrl key is pressed. But when the document area is active, the code doesn't fire.
Background: I am thinking of having the ability to use Chrome extensions with Google Apps Script to define custom hotkeys, just faced the problem of not firing events in the active document area.
While it is not visible, Docs editing content is within an iframe. Your content_script is not loading on iframes.
You can enable this by adding to new rules to your content_scripts in manifest.json:
"all_frames": true,
"match_about_blank": true
The first allows your code to load on frames. The second one allows to load on empty pages (and frames). Together with your current manifest.json:
{
"manifest_version": 2,
"name": "My Cool Extension",
"version": "0.1",
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["jquery.js", "content.js"],
"all_frames": true,
"match_about_blank": true
}
],
"permissions": [
"tabs"
]
}
Use the chrome.commands API instead of jQuery.

Content script doesn't support chrome settings page (url : chrome://history/ etc. )

I am working with a chrome extension . I want to inject js script in all tab. I am using this manifest.json :
{
"name": "ABC",
"version": "0.0.1",
"manifest_version": 2,
"background": {
"scripts": [
"src/background/background.min.js"
],
"persistent": true
},
"browser_action": {
"default_icon": "icons/128.png",
"default_title": "ABC",
"default_popup": "src/browser_action/index.html"
},
"permissions": [
"tabs",
"http://*/*",
"https://*/*",
"<all_urls>"
],
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["./src/inject/inject.min.js"],
"css": ["./css/inject.min.css"],
"all_frames": true
}]
}
And my inject.js is like this :
(function() {
console.log("Hello");
});
I am getting all log from all tab except the tab of the chrome setting (eg : chrome://extensions/:id , chrome://history etc).
Am I missing something in manifest.json or chrome disables the feature of injection in settings page ?
Thanks in advance.
Indeed, you can't inject code into chrome:// pages. They contain control elements / code that can modify the browser in ways that an extension is not allowed to.
Chrome resolves this by simply not allowing permissions to be set for chrome:// URLs, and <all_urls> does not include it.
However, you could use Override Pages to replace some of them (well, History page at least) completely.

Default popup matching URL

I test an online-survey application. I have hundreds of textboxes in my application in which I have to enter some numbers for testing purposes. So I am creating a Chrome extension to fill the form. I did it and it works almost as I expected - except there is a small issue.
manifest.json:
{
"name": "FillForm",
"version": "1.0",
"manifest_version": 2,
"description": "FillForm",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": ["activeTab"]
}
Whenever I click on the browserAction button - it opens the popup.html where there is a textbox. If I enter 1 there, it will enter 1 for all the textboxes in my application - this is what I wanted.
Now I want to open the popup.html only for my application, i.e. matching URL http://example.com, because I do not want to enter any information in any other pages.
How can i achieve this?
I would inject the content of your popup.html in the pages matching specified URL.
This simplify your actions to fill your forms (you do no have to click on the extension icon)
It does not glut your browser with an additional icon
For doing this, first modify your manifest:
{
"name": "FillForm",
"version": "1.0",
"manifest_version": 2,
"description": "FillForm",
"content_scripts": [
{
"matches": ["http://*.xxx.com/*"], // put your URL pattern here
"js": ["popup_inject.js"]
}
],
"web_accessible_resources": ["popup.html"]
"permissions": ["activeTab"]
}
and in popup_inject.js
var iframe = document.createElement ("iframe");
iframe.src = chrome.extension.getURL ("popup.html");
iframe.style.position="absolute";
iframe.style.top="10px";
iframe.style.right="10px";
iframe.style.border="solid 1px #aaa";
document.querySelector("body").appendChild(iframe);
This is the exact purpose of Page Actions: to provide a button that's only visible on certain websites.
First, change your browser_action key to a page_action:
"page_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
You need to decide yourself when to show it. With declarativeContent API, you can provide a set of rules that say when you want to do it.
Add the declarativeContent permission:
"permissions": ["activeTab", "declarativeContent"]
Then, add a background script that will manage the rules. Since you don't need the background script to be always active, it's a good fit for an Event Page.
"background": {
"scripts": ["eventPage.js"],
"persistent": false
},
Now, the event page code:
// eventPage.js
// This only needs to run on install/update, rules are remembered
chrome.runtime.onInstalled.addListener(function(details) {
var rule1 = {
conditions: [
new chrome.declarativeContent.PageStateMatcher({
// See declarativeContent docs for more options
pageUrl: { hostEquals: 'www.example.com' }
})
],
actions: [ new chrome.declarativeContent.ShowPageAction() ]
};
// Remove existing rules, if any
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
// Then, add our rule1
chrome.declarativeContent.onPageChanged.addRules([rule1]);
});
});

Chrome Extension - edit a text field

I'm trying to write my first Chrome extension. It would, when clicked, automatically fill the fields of an ID and password for my University's login page (which has its form's auto-fill disabled).
It's a very specific page.
I have a few problem.
I've searched Google and SO but couldn't find an explanation on how to change the value of a text field through Chrome. I know how to do this in HTML and JavaScript, however I couldn't get the proper input to modify its text.
I've also tried using jQuery using a few examples I've found, but no luck.
I have an HTML page (popup.html) which calls a JavaScript file.
I've also tried placing the JS in a content script
Here's the manifest.json:
{
"name": "My First Extension",
"version": "1.0",
"manifest_version": 2,
"description": "The first extension that I made.",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"tabs", "http://*/*"
],
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["jquery-1.7.2.min.js","content.js"]
}
]
}
One of my attempt of popup.js (which gets called from popup.html) is:
chrome.tabs.getSelected(null, function(tab) {
console.log(document)
});
I've also tried placing this code inside the content.js. same result,
It prints to console, however it prints the popup.html content..
I've also tried directly (and from the above method) to access an element directly by document.getElementById() but still no luck..
So,
Can anyone tell me what I'm doing wrong?
You need to inject a JavaScript file to the page using the "web_accessible_resources" attribute. See here:
manifest.json
{
"name": "My First Extension",
"version": "1.0",
"manifest_version": 2,
"description": "The first extension that I made.",
"browser_action": {
"default_icon": "icon.png"
},
"permissions": [
"tabs", "http://*/*"
],
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["jquery-1.7.2.min.js","content.js"],
"run_at": "document_start"
}
],
"web_accessible_resources": ["inject.js"]
}
inject.js
(function () {
console.log('test');
}());
content.js
(function (chrome) {
var js = document.createElement('script');
js.type = 'text/javascript';
js.src = chrome.extension.getURL('inject.js');
document.getElementsByTagName('head')[0].appendChild(js);
}(chrome));
Then just put the JavaScript code you want to use in inject.js to manipulate the page. Be sure to change matches to only match your University's login page.
The reason this is the case is because Chrome extensions can run and operate on their own regardless of which website you're on. And they can continue to process as you switch pages. They're in their own sandboxed environment.
I think you should use a simple content script that is executed on the login page. You don't even need any browser action or popup for that.
Here's a manifest:
{
"name": "Fill my password",
"version": "1.0",
"manifest_version": 2,
"description": "Fills my password on University login page",
"content_scripts": [
{
"matches": ["http://www.myuniversity.edu/login.html"],
"js": ["content.js"]
}
]
}
And here's a content script:
// define your username and password
var myUsername = '...';
var myPassword = '...';
// find the fiends in your login form
var loginField = document.getElementById('...');
var passwordField = document.getElementById('...');
// fill in your username and password
loginField.value = myUsername;
passwordField.value = myPassword;
// if you want, you can even automaticaly submit the login form
var loginForm = document.getElementById('...');
loginForm.submit();
Possible workaround(chrome extension): Autocomplete = on, but it could not work with some forms.

Categories

Resources