Cannot call chrome.alarms.create() from a content script - javascript

I'm developing a Chrome extension right now.
My problem is that when I call chrome.alarms.create(), I get the following error:
Uncaught TypeError: Cannot read property 'create' of undefined
I have these files in my extension package:
manifest.json
{
"manifest_version": 2,
"name": "Tool",
"version": "1.0",
"background": {
"scripts": ["background.js"]
},
"permissions": ["background", "tabs", "webNavigation", "alarms"]
}
myscript.js
chrome.alarms.create("aaa", {"when":Date.now()+5000});
chrome.alarms.onAlarm.addListener(function(alarm){
console.log("hello");
});
background.js
chrome.pageAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, {file: "myscript.js"});
});
When I call chrome.alarms.create() in background.js, it works fine.
But, when I call the function in myscript.js, it causes the error.
What is the cause and how can I fix this problem?

You can't access most Chrome APIs from a content script. You will need to use the Messaging API to send a message to the background page which can then call the Alarms API.
https://developer.chrome.com/extensions/messaging
https://developer.chrome.com/extensions/content_scripts

Related

`alert` not showing in ManifestV3 background service worker

I am trying to make a chrome extension that alerts you in the tab that you are currently moving or highlighting. I have tried reading the chrome migrating to V.3 documentation and have come up with the following code, however, the alerts never appear. Does anybody know what I need to change or add?
// manifest.json
{
"manifest_version": 3,
"name": "Alert",
"version": "0.1",
"description": "alerts you when doing tab functions",
"permissions": ["tabs", "activeTab"],
"host_permissions": ["<all_urls>"],
"background": {
"service_worker": "background.js"
}
}
//background.js
chrome.tabs.onMoved.addListener(function () {
alert("You moved this tab");
});
chrome.tabs.onHighlighted.addListener(function () {
alert("You highlighted this tab");
});
Working directory:
.
├── background.js
├── manifest.json
alert() method cannot be used outside of the browser environment, you can use console.warn() or console.error() instead. But is not a good solution if you want to show an error message to the extension user, as they would never open the console.
If you would like a more user friendly approach use the following:
chrome.notifications.create({
type: 'basic',
iconUrl: '/images/image_if_any.png',
title: `Notification title`,
message: "Your message",
priority: 1
});
Also add "notifications" to "permissions" in your manifest.json file:
"permissions": [..., "notifications"]
alert is not defined in a service worker per specification so we'll have to use console.log
Also, I was looking in the wrong place for the alert messages. I needed to look at the service worker link in my unpacked extension page.

Chrome.identity not working in popup.js?

I'm trying to get the userInfo object from chrome.identity.getProfileUserInfo in my popup.js (which is a script used for popup.html) but I am getting the following error:
Uncaught TypeError: Cannot read property 'getProfileUserInfo' of undefined at onload
popup.js
onload = function(){
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
var url = tabs[0].url;
console.log(url);
});
chrome.identity.getProfileUserInfo(function(userInfo)
{
console.log(userInfo)
});
}
manifest.json
{
"manifest_version": 2,
"name": "QuickLink",
"description": "This extension allows you to quickly shorten and/or customize your url",
"version": "1.0",
"browser_action":
{
"default_icon": "icon.png",
"default_popup": "popup.html",
"default_title": "QuickLink"
},
"permissions":
[
"background",
"activeTab",
"clipboardWrite",
"tabs",
"notifications",
"identity",
"runtime"
]
}
I believe I have all the right permissions, and my tabs query works just fine, but for some reason, I don't have access to chrome.identity...any ideas why this might be or any work arounds so I can get the userInfo?
Would appreciate any help, thanks!
As answered in this thread you can only access it with a background script, not a content script.
It may require providing a "key" value in your manifest as well (if you're trying to get it working locally and it's not working). You can either use the same key as the one you get when you upload your extension to the webstore or try packing an extension to generate a new one (though I couldn't get this second approach working myself).

Uncaught TypeError: Cannot set property 'textContent' of null (Detailed)

Have searched a ton, can't find a solution. Am making a chrome extension. Here is what I have:
Manifest:
{
"name": "Test",
"description": "T",
"version": "2.0",
"permissions": [
"activeTab"
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {
"default_title": "Stuff"
},
"manifest_version": 2
}
Background.js:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, {file: "content_script.js"});
});
content_script.js:
console.log(document.getElementById('DERIVED_SSTSNAV_PERSON_NAME'));
document.getElementById('DERIVED_SSTSNAV_PERSON_NAME').textContent = "test";
"Copy Element" off the page I'm working with:
<span class="PALEVEL0PRIMARY" id="DERIVED_SSTSNAV_PERSON_NAME">John Smith</span>
So, when I type both of those content_script.js ^ lines of code into console, I get what I want. I first get the whole <\span class...span>. Then .textContent spits out "John Smith." Fine and dandy.
The second I throw run my chrome script with the. exact. same. lines of code, I get "null" instead of <\span class...span> and then trying to access the .textContent throws me the error in my title.
What the heck? Seriously. I've spent hours redoing my manifest and trying to get that to work, but I can edit the DOM on other pages, just not this one. Would love to chat and get some feedback.
Thank you.

How to create a chrome (extension) webRequest listener?

I am trying to create a chrome (extension) webRequest listener. However, no matter what I try I cannot get access to the chrome.webRequest object - my program crashes with Uncaught TypeError: Cannot read property 'onCompleted' of undefined. Also debugging on the command line shows that chrome.webRequest does not exist.
My suspicion is that I am doing something wrong in the permissions, as I did not see many other stackoverflow questions or chrome bug reports with the same issues.
This is my manifest.json
{
"manifest_version": 2,
"name": "my extension",
"description": "my extension description",
"version": "1.0",
"permissions": [
"activeTab",
"webRequest",
"webRequestBlocking",
"https://<myextension>.com/*",
],
"page_action": {
"default_icon": { // optional
"19": "myextension.png", // optional
"38": "myextension.png" // optional
}
},
"content_scripts": [
{
"matches": ["https://<myextension>.com/*"],
"css": ["myextension.css"],
"js": ["jquery.js", "myextension.js"]
}
]
}
This is my myextension.js
var myfilter = {
urls: ['https://myextension.com/*']
}
function mycallback(){
console.log('received request response');
}
chrome.webRequest.onCompleted.addListener(mycallback, myfilter);
Any idea what I might be doing wrong?
I am running OSX 10.10.2 and chrome 40.0.2214.94.
Most of the Chrome API cannot be used in Content Scripts, including webRequest:
However, content scripts have some limitations. They cannot:
Use chrome.* APIs, with the exception of:
extension ( getURL , inIncognitoContext , lastError , onRequest , sendRequest )
i18n
runtime ( connect , getManifest , getURL , id , onConnect , onMessage , sendMessage )
storage
You need to process this event in a background page and communicate with the context script using Messaging.

Setting local storage in a Chrome extension

I'm using the following code to set local storage in a Chrome extension.
localStorage.setItem('userkey','123');
/* I've also tried this:
chrome.storage.sync.set({'userkey': 123}, function() {
// Notify that we saved.
message('Settings saved');
});
*/
manifest.json:
{
"manifest_version": 2,
"name": "Shopaholic",
"description": "All the latest sale items from your favourite clothes shops right on your home screen",
"version": "1.0",
"chrome_url_overrides": {
"newtab": "index.html"
},
"content_scripts": [
{
"matches": ["*://*/index.html"],
"css": ["css/style.css"],
"js": ["js/jquery.min.js"]
}
],
"options_page": "options.html",
"permissions": [
"storage"
]
}
However, I'm getting this error:
Uncaught SecurityError: Failed to read the 'localStorage' property
from 'Window': The document is sandboxed and lacks the
'allow-same-origin' flag.
If I use the commented out code above, I get:
Uncaught TypeError: Cannot read property 'sync' of undefined
Where have I gone wrong?
Read this - https://en.wikipedia.org/wiki/Same_origin_policy
Basically, its a web application security model concept.
So, to avoid this u need to disable the same origin policy on google chrome
So, if on desktop, open chrome from command line with this command
chrome.exe --disable-web-security
and then run your script, it shouldn't give this error then!

Categories