I'm trying to get this
optional permission dialog to pop up locally while testing
I've been following this official tutorial:
https://developer.chrome.com/docs/extensions/reference/permissions/
In my case, the optional permission dialog should ideally activate when the button of class '.cbtn' is clicked on my website.
Here is chrome.permission.request part of my background.js file
document.addEventListener("DOMContentLoaded", function(event) {
document.querySelector('.cbtn').addEventListener('click', function(event) {
console.log('now activating prompt!!');
chrome.permissions.request({
permissions: ["bookmarks"]
}, function(granted){
// The callback argument will be true if the user granted the permissions.
if (granted) {
// doSomething();
console.log('Access granted');
} else {
// doSomethingElse();
console.log('Access denied');
}
});
});
});
Note: My manifest.json doesn't contain permission for bookmarks.
In the chrome://extensions/?errors for my unpacked extension, i see an error message-
"Uncaught TypeError: Cannot read property 'addEventListener' of null"
I don't know if that is because it's trying to find .cbtn on the chrome://extensions/ page itself instead of on my particular website where a button with class .cbtn actually exists,
Will appreciate any help, pointers on this
Related
I'm developing my first chrome extension and I'm stuck with a "session restore" problem. At the begging of the developement when a user log in to my extension and close the popup, when he open the plugin again he had to login again.
I've used chrome.storage.sync to be able to save the session infomation to make the user to be still logged in and if he close the plugin, and his session is still active he will be redirected to the welcome page. But how can I check at the extension's startup in what page of the plugin the user was and bring him back to that page?
For example, if a user is logged and was on the "choose a book" section, how can i make the plugin open at "choose a book" section and not in "welcome" section?
Angular 2 for client side
NodeJs for server side
Consider that the session object is something like:
{
logged: true,
last_section: 'books'
}
When the user visits the books section, save it.
// this code goes inside some listener for visiting a section
chrome.storage.sync.get('session', function (items) {
const session = items.session || {}
session.last_section = 'books'
chrome.storage.sync.set({ session })
})
At the beginning of the popup script, you can simply call chrome.storage.sync.get to get the last session object state.
chrome.storage.sync.get('session', function (items) {
const session = items.session
if (session && session.logged) {
if (session.last_section === 'books') {
// render books section
}
if (session.last_section === 'welcome') {
// render welcome section
}
}
})
write an extension get the mediastream from current tab by using chrome.tabCapture.capture
In content-script.js, i send a message to background.js
$("video").bind('play',function(event){
port.postMessage("get-stream");
});
In background.js handle the message
function portOnMessageHanlder(message) {
chrome.tabCapture.capture(config,function(stream){...});
}
but got an error
Unchecked runtime.lastError while running tabCapture.capture: Extension has not been invoked for the current page (see activeTab permission)
In manifest file grants the access permssion as follows:
"permissions": [
"tabs",
"activeTab",
"tabCapture",
]
also check the chrome extension document , it says need to get active tab by browserAction,so i add setIcon when handler the message from content-script.js
function portOnMessageHanlder(message) {
if(message != 'get-stream'){
if(message == "set-icon"){
chrome.browserAction.setIcon({
path: 'recordRTC-progress-1.png'
});
}
return;
}
chrome.tabCapture.capture(config,function(stream){
if(!stream){
return port.postMessage('PermissionDeniedError');
}
port.postMessage({stream:stream});
});
return;
}
but still got the permission deny error.
any advice ? thanks
Background page:
chrome.tabs.create({ url: 'http://google.com' }, tab => {
chrome.tabs.executeScript({ code: '2+2;' }, (r) => {
console.log(`url: ${tab.url}, result: ${r[0]}`);
});
});
I open background page to see output:
url: http://google.com/, result: 4
Looks good, but now I press F5 or Ctrl+F5:
Unchecked runtime.lastError while running tabs.executeScript: Cannot access contents of url "chrome-devtools://devtools/bundled/inspector.html?&remoteBase=https://chrom…om/serve_file/#e8926f681fbb840b4f389e7e692343d4505722ce/&dockSide=undocked". Extension manifest must request permission to access this host.
at Object.callback (chrome-extension://laaoiaaacchfpefjhklpmnfjbeamjfli/background.js:2:15)
In 'manifest.json' I have <all_urls> permission.
When the first parameter, tabId, of chrome.tabs.executeScript is omitted the code is injected into the active tab of the active window. In your case the active window is the devtools debugger of the background page and it doesn't allow injection of code.
Specify tabId explicitly: chrome.tabs.executeScript(tab.id, { code: .......
I use a extension inner page(chrome-extension://) to request permission, and send result to background.
in extension inner page:
btn.addEventListener('click', function(event) {
event.preventDefault();
chrome.permissions.request({
permissions: permissions,
origins: origin
}, function(granted) {
chrome.runtime.sendMessage({route: '/permissionRequest', data: {command: 'Response', result: granted}}, function(){});
});
}, false);
It looks well.But when I click the button, it open a new tab, url like chrome-extension://.../authorizehtml?undefined. The message send.
I don't know why it open a new tab like that.
And the, I found, if I change the key name 'data' to other name, it never open new tab.The official document don't talk about it.
I hava no idea about it.
I'm trying to pass data that is saved in sessionStorage from background.html to popup.html
background.html:
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
data = sessionStorage.getItem(request.tabId);
alert(data);
sendResponse({ data: data });
});
and in popup.html:
chrome.tabs.getSelected(null, function(tab) {
chrome.extension.sendRequest({ tabId: tab.id }, function(response) {
alert(response.data);
});
});
The popup is opened by a pageAction button, when I click the button I get an alert box with "null" on the popup and then an alert box with the data that I stored in sessionStorage on the background!
Any ideas how to fix this?
You don't need to use message/request APIs. I think this response may help you.
You also don't need sessionStorage, just store your data in a global variable of the background page. It will persist until the browser is closed or until the extension is restarted.
So, here is how I would rewrite your code:
background.html:
var data = {}; // Object storing data indexed by tab id
and in popup.html:
chrome.tabs.getSelected(null, function(tab) {
alert(chrome.extension.getBackgroundPage().data[tab.id]);
});
Note that chrome.tabs.getSelected is deprecated since Chrome 16, so popup code should be:
chrome.windows.getCurrent(function(win) {
chrome.tabs.query({'windowId': win.id, 'active': true}, function(tabArray) {
alert(chrome.extension.getBackgroundPage().data[tabArray[0].id]);
});
});
Well, I've done something dumb.
I inspected the background page by opening chrome-extension://[extension-id]/background.html in a tab instead of clicking on "inspect active views: background.html" in the extensions management page. This caused the tab to catch the request and call sendResponse, but the popup expected the REAL background page to call sendResponse (and if I understand Google's documentation regarding message passing, the fact that sendResponse was called twice is root of the problem, because the first call clears the request object)