chrome.idle is undefined in chrome extension - javascript

I'm trying to implement a simple idle detection in chrome.
I created an extension with this permission:
"permissions": [
"webNavigation",
"storage",
"tabs",
"*://*/*",
"idle"
],
"background": {
"scripts": ["js/background.js"]
},
"content_scripts": [
{
"run_at": "document_start",
"matches": [
"*://*/*"
],
"css": [
"css/content.css"
],
"js": [
"js/jquery.min.js",
"js/content.js"
]
}
]
and in content.js
$(function () {
console.log('init idle detection');
chrome.idle.queryState(5, function(newState){
//"active", "idle", or "locked"
if(newState === "idle"){ alert(newState); }
});
...init other things...
});
however, chrome.idle is always undefined.

According to documentation, content scripts cannot access idle API. Use it in background script (or popup script) and communicate with content script via messaging.
From the documentation:
Content scripts can access Chrome APIs used by their parent extension
by exchanging messages with the extension. They can also access the
URL of an extension's file with chrome.runtime.getURL() and use the
result the same as other URLs.
//Code for displaying <extensionDir>/images/myimage.png:
var imgURL = chrome.runtime.getURL("images/myimage.png");
document.getElementById("someImage").src = imgURL;
Additionally,
content script can access the following chrome APIs directly:
i18n
storage
runtime:
connect
getManifest
getURL
id
onConnect
onMessage
sendMessage
Content scripts are unable to access other APIs directly.
(Bold type on last line added)

Related

Auto start chrome extension

I am trying to make a chrome extension that redirects to a other page when it's loaded. For example, if it's google.nl, go to google.nl?example I managed to get that working, but only when i press the extension button. I want to run the script from the background.js but i get the error:
Uncaught TypeError: Cannot read property 'onBeforeRequest' of undefined
Why do i wan't to reload? Well i don't. it's just to test. The original plan is reading the URL and put the open graph data in my extension.
manifest (part)
"content_scripts": [{
"matches": [
"<all_urls>"
],
"js": ["background.js"]
}],
"permissions": [
"tabs",
"activeTab",
"webRequest"
],
"background": {
"scripts": ["background.js"]
}
background.js
chrome.webRequest.onBeforeRequest.addListener(function(a) {
if (a.url.indexOf("http://www.google.com/") >= 0) {
reloadExtensions();
chrome.tabs.get(a.tabId, function(b) {
if ((b.selected == false)) {
chrome.tabs.remove(a.tabId)
}
});
return {redirectUrl: chrome.extension.getURL("close.html")}
}
return {cancel: false}
}, {urls: ["http://reload.extensions/"],types: ["main_frame"]}, ["blocking"]);
iirc the docs say you need to put all the URL's you want to redirect in the permissions array.
If you don't you will see the following error
Checkout Catblock example https://developer.chrome.com/extensions/samples#search:webrequest by removing
I don't think you need the content script parts at all, in fact I suspect that is where you are seeing the error.

chrome.extension.getBackgroundPage is undefined in an extension page in an iframe

I am trying to access my extension's background page using chrome.extension.getBackgroundPage function.
However, I get the following error:
Uncaught TypeError: chrome.extension.getBackgroundPage is not a function
I am calling the function from my bar.js file which is defined as a web_accessible_resource in my manifest.json
How do I make it work?
manifest.json
{
"manifest_version": 2,
"name": "XPath Helper",
"version": "1.0.13",
"description": "Extract, edit, and evaluate XPath queries with ease.",
"background": {
"page": "background.html"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"css": ["content.css"],
"js": ["content.js"]
}
],
"permissions": ["http://*/", "tabs", "identity", "identity.email"],
"icons": {
"32": "static/icon32.png",
"48": "static/icon48.png",
"128": "static/icon128.png"
},
"web_accessible_resources": [
"bar.css",
"bar.html",
"bar.js"
]
}
bar.js is a script inside bar.html (not a content script):
// ...
document.addEventListener('DOMContentLoaded',function(){
// previosuly chrome.extension.getBackgroundPage()
chrome.runtime.getBackgroundPage(function(page){
alert("hello");
})
})
content.js
// ...
this.barFrame_ = document.createElement('iframe');
this.barFrame_.src = chrome.extension.getURL('bar.html');
document.body.appendChild(this.barFrame_);
// ...
Most extension APIs can only be used if the page runs in the extension process, i.e. the top-level frame is a non-sandboxed chrome-extension: page.
chrome-extension:-frames in a non-extension process can only access the extension APIs available to content scripts and web pages. And unlike content scripts, they can also use web platform APIs at the extension's origin. For example, if you use localStorage in a content script, then the DOM storage of the page where the content script runs is accessed. If you use localStorage in a chrome-extension: page, then you'll get the extension's storage.
If you want to access functionality of the background page in your frame, use the extension messaging APIs to communicate between your frame and background page.

Chrome Extension: how to change JS url before he starts loading

I wanna change src of js javascript before he starts loading using a Chrome Extension.
Manifest.json
{
"name":"Inject DOM",
"version":"1",
"manifest_version":2,
"permissions": [
"webRequest",
"webNavigation",
"http://*/*",
"https://*/*"
],
"content_scripts": [
{
"run_at": "document_end",
"matches": ["http://www.example.com/*"],
"js": ["inject_this.js"]
}
]
}
inject_this.js
I execute this code in various functions scenarios
var element = event.srcElement;
if(/production_path/.test(element.src)){
element.src = element.src.replace(/production_url/gi, "dev_path");
}
Scenario A
document.addEventListener('DOMNodeInserted', nodeInsertedCallback);
Scenario B
Executing this scenario into inject_this.js throw this TypeError:
Uncaught TypeError: Cannot read property 'onBeforeRequest' of undefined
Executing this in another js doesn't work
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
if(/production_url/.test(details.url)){
return {
redirectUrl: details.usl.replace(/production_url/gi, "dev_url")
}
}
},
{urls: ["<all_urls>"]},
["blocking"]);
Where do i put this snippet code ?
Scenario C
document.addEventListener('beforeload', doBeforeLoad , true);
but every time script.src is changed too late, the resource is loaded.
How can I change javascript url before he starts loading?
Your solution B should work.
Two conditions need to be met for this to work:
This code should go to a background script / event page.
You need appropriate permissions: "webRequest", "webRequestBlocking"
You probably also should not use it on <all_urls>, since your extension seems to be specific to a single site (from your manifest). Doing it on all URLs is going to slow your Chrome down and may lead to breaking other sites, consider using a restrictive match pattern like "http://www.example.com/*production_url*"

Chrome extension inject js

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"});
});

Chrome extension: Javascript content script does not have access to HTML elements

I've looked at some similar threads in SO but I couldn't understand the solutions.
Here is my code:
manifest.json
{
"name": "Test 5",
"version": "1.0.0",
"manifest_version": 2,
"permissions": [
"storage",
"tabs",
"http://*/*"
],
"web_accessible_resources": ["jquery-2.0.3.min.map"],
"content_scripts": [
{
"matches": [
"*://*.google.es/*"
],
"js": ["jquery.js", "content_scripts.js"],
"run_at": "document_end",
"all_frames": true
}
]
}
content_scripts.js
var doFilter = function() {
var classR = document.getElementsByClassName("rc");
console.log("2");
console.log("classR: "+classR.length );
//...etc
}
$(window).load(function() {
console.log("1");
doFilter(document.body);
});
The code is already loaded as a Chrome unpacked extension. I'm using Dev Tools in Chrome to debug it from the local files in my PC.
When having Dev Tools opened in the same tab as the web browser, I browse to "www.google.es" and I search for some keyword.
Then I'm able to see in Dev Tools console logs. The problem is that the last one shows that classR has length 0.
As you can see, there are elements by class name "rc", so it seems
document.getElementsByClassName("rc")
is actually not accessing to the loaded HTML document.
What am I missing here?
Thanks.

Categories

Resources