Chrome.identity not working in popup.js? - javascript

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).

Related

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.

JQuery 3.1 failing to grab DOM when used inside chrome content scripts

I am new to developing chrome extensions, though I understand the concept of content scripts and isolated worlds. I just can't grasp the actual issue.
I am aware there is a lot of posts in StackOverflow for Jquery not working in Content Scripts ( Chrome Extension ). Most do not seem to address why.
My Code as follows
Manifest.json
{
"manifest_version": 2,
"name": "TestExtension",
"description": "Chrome Extension",
"version": "1.0",
"browser_action": {
"default_icon": "img/icon.png",
"default_popup": "popup.html",
"default_title": "MyExtension"
},
"content_scripts":[{
"js":["js/lib/jquery-3.1.1.min.js","js/app/content.js"],
"matches":["<all_urls>","http://*/*","https://*/*"],
"run_at":"document_start"
}],
"content_security_policy": "script-src https://*.google.com 'unsafe-eval'; object-src 'self'",
"minimum_chrome_version":"22",
"web_accessible_resources" : [
"js/lib/jquery-3.1.1.min.js"
],
"permissions": [
"activeTab",
"http://*/*",
"https://*/*",
"unlimitedStorage",
"contextMenus",
"cookies",
"tabs",
"notifications",
"identity",
"*://*.google.com/*"
],
}
I am trying to grab some DOM content from gmail.
I have used content script matches pattern to all urls for test purposes.
And so is Content Security Policy (unsafe-eval) and Web_Accessible_Resources ( Trial and error stuff )
I have provided almost all the permissions to check whats causing the issue.
Content.js
console.log('I am Content Script');
var jq = $.noConflict();
if (typeof jq == 'undefined') {
console.log('JQuery Not Loaded');
}else{
console.log('JQuery Loaded');
}
jq(document).ready(function(){
console.log(document.getElementsByClassName("editable"));
console.log(jq("body").className);
});
Output:
The Content Script gets injected to the Page.
The Jquery is loaded. And I have used noConflict() to make sure i am not running into any internal script conflicts.
The Vanilla JS grabs the DOM element.
But the Jquery fails not grab anything. No error messages shown.
Question:
I am aware of the "chrome.runtime.sendMessage" and "chrome.runtime.onMessage" and its neccessity during messaging. But do i have to wrap the logic inside this onMessage ?
Also, I have seen some solutions using the script injection ( chrome.tabs.executeScript ) , But is it the only solution. I feel like i am missing something in manifest.json could someone point out if i have missed something ?
Thanks in advance.

Chrome Runtime OnMessage Listener event not firing

script/contentscript.js
'use strict';
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
alert("hi");
return true;
});
chrome.runtime.sendMessage(null, {hello:"hello"});
I'm at a loss. Either addListener isn't registering the callback, the callback isn't being fired when a message is sent, or something in between. I've done what I can to limit the possible errors. At one point the sendMessage was in my popup.js and after hours of trying different variations, I ported it to another computer. When I got desperate enough to put the sendMessage in the same file it was a surprise to find sendMessage wouldn't work even in the same contentscript!
I've used both runtime and tabs objects as well as every variation of both sendMessage and onMessage.addListener.
One odd thing is that when on a breakpoint in the content script, I've seen hasListener usually return false and hasListeners return true after my listener is added.
{
"name": "__MSG_appName__",
"version": "0.0.1",
"manifest_version": 2,
"description": "__MSG_appDescription__",
"icons": {
"16": "images/icon-16.png",
"128": "images/icon-128.png"
},
"default_locale": "en",
"content_scripts":[
{
"matches": ["http://*/*", "https://*/*"],
"js":["scripts/contentscript.js"]
}
],
"browser_action": {
"default_icon": {
"19": "images/icon-19.png",
"38": "images/icon-38.png"
},
"default_title": "pluralsight dl",
"default_popup": "popup.html"
},
"options_page": "options.html",
"permissions":[
"activeTab",
"tabs",
"http://*/*",
"https://*/*"
]
}
Any ideas on why this wouldn't work? Both computers are using Version 43.
A popup js message that also doesn't register. Same extension package.
script\popup.js
'use strict';
console.log('\'Allo \'Allo! Popup');
// File executed, it's ready for the message
chrome.runtime.sendMessage(null, { action: "start"});
sendMessage never fires the event in the same context. Only other contexts receive the message.
As for your initial problem, there are 2 forms of sendMessage: runtime.sendMessage sends messages to extension's own pages (origin chrome-extension://yourId/) and tabs.sendMessage that sends messages to content scripts. See this question for more details.

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.

Chrome Extension that loads Page Source of the active tab

I hope you can help me.
I am trying to create an extension in Chrome which would load a source of the active tab into a variable.
So far I have:
manifest.json
{
"name": "My Extension",
"manifest_version": 2,
"version": "0.1",
"description": "Does some simple stuff",
"browser_action": {
"default_icon": "logo.png"
},
"background": {
"scripts": ["main.js"]}}
main.js
chrome.browserAction.onClicked.addListener(
function(tab) {
var ps1 = document.getElementsByTagName('html')[0].innerHTML;
window.alert(ps1);
});
but that loads the page source of the blank page. What do I need to do to get the source of the active page.
I have done some reading and I think I need to use content script whit some listening functions, I have been searching but all answers seem to me very complicated. Would any of you be so kind to give me some easy example?
Highly appreciate your feedback!
Regards
UPDATE after AdrianCooney answer:
I changed my manifest to contain
"permissions": [
"tabs"
]
Then in main.js I did
chrome.browserAction.onClicked.addListener(function(activeTab) {
chrome.tabs.query({ currentWindow: true, active: true },
function (tabs) {
var ps1=document.getElementsByTagName('html')[0].innerHTML;
window.alert(ps1);
})
});
When I press the Extension button I get something like that
<html></html>
<body><script src="main.js"></script>
</body>
...no matter what tab I have active.
Another try with chrome.tabs.getCurrent
chrome.browserAction.onClicked.addListener(function(activeTab) {
chrome.tabs.getCurrent(
function (tabs) {
var ps1=document.getElementsByTagName('html')[0].innerHTML;
window.alert(ps1);
})
});
The above version of main.js give exact same output as the one before, no matter what page I have active.
Background scripts are isolated from the current page because they're designed to be persistant regardless of the content of the page. You need to use the chrome.tabs API, specifically chrome.tabs.getCurrent. Once you have the current tab, you can inject code into the window. That's where your snippet above comes in.
You will need to add "tab" to your permissions in the manifest file.
As was pointed out, you need to run code in the context of the active tab. One way to do it is using chrome.tabs.executeScript:
chrome.browserAction.onClicked.addListener( function() {
chrome.tabs.executeScript(
{
code: "document.getElementsByTagName('html')[0].innerHTML;"
},
function (ps1) {
window.alert(ps1);
}
);
});
This code under main.js works!!! Thank you guys for your hints they saved me a lot of time!
chrome.browserAction.onClicked.addListener(
function(tab) {
chrome.tabs.executeScript(
null,{
code:"var ps1 = document.getElementsByTagName('html')[0].innerHTML;
window.alert(ps1);"});
}
);
In Chrome 47 you need to add "activeTab" to permissions, otherwise it doesn't work. With "tabs" it doesn't work.
manifest.json:
{
"name": "Rafi extension",
"manifest_version": 2,
"version": "7",
"description": "Open something",
"browser_action": {
"default_icon": "logo.png"
},
"permissions": [
"activeTab"
],
"background": {
"scripts": ["main.js"]}
}
For anyone looking to do this with Manifest V3, things are much simpler. Let's say you have a script parse_page.js in the root of your extension, that contains whatever code you want to execute:
var ps1 = document.getElementsByTagName('html')[0].innerHTML;
window.alert(ps1);
From the docs, there are two ways to have it execute:
(1) Inject with static declarations: use this method for scripts that that need to run automatically. Simply add the following to your manifest.json:
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["parse_page.js"]
}
],
The script will run whenever you visit a new page. You can adjust the matches above if you only want it to execute on certain URLs.
(2) Inject programmatically: use this method for scripts that need to run in response to events or on specific occasions. Add the following to your manifest.json:
"permissions": ["activeTab", "scripting"],
"background": {
"service_worker": "background.js"
},
"action": { }
Next, in background.js, add the following:
chrome.action.onClicked.addListener((tab) => {
chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ['parse_page.js']
});
});
In this example, the script will run whenever you click on your extension's icon.

Categories