I'm trying to access serial/usb ports via chrome plugins/extensions. Im following the documents from chrome usb && chrome serial , when i started my plugin it throws
"Uncaught TypeError: Cannot read property 'getDevices' of undefined"
i also tried the sample codes from google chrome sample but experienced the same problem, basically chrome.usb / chrome.serial is undefined.
Any suggestions to put me right direction is appreciated. Thanks !
Im attaching my sample codes
popup.html
<!DOCTYPE html>
<html>
<body style="width: 300px">
Open this page and then
<button id="clickme">click me</button>
<script type="text/javascript" src="popup.js"></script>
</body>
</html>
popup.js
function readPorts() {
console.log("Reading ports . . . . . ")
chrome.usb.getDevices(function(devices) {
console.warn('chrome.usb.getDevices error: ' +
chrome.runtime.lastError.message);
for (var i = 0; i < devices.length; i++) {
console.log('Device : ' + devices[i].path + '"===' + devices[i].path + '=====');
}
});
}
document.getElementById('clickme').addEventListener('click', readPorts);
manifest
{
"manifest_version": 2,
"name": "Getting started example",
"description": "This extension will read the com ports from your machine",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html",
"default_title": "Read com ports!"
},
"content_scripts": [
{
"matches": ["http://*/*","https://*/*"],
"js": ["myscript.js"]
}
],
"permissions": [
"serial",
"usb"
]
}
Only Chrome Apps (not Chrome Extensions) have access to the hardware. Check the steps for creating a Chrome App: https://developer.chrome.com/apps/first_app
Both of those APIs are limited to Chrome Apps. Your manifest specifies an extension.
Chrome Extensions have an entirely different set of APIs. They overlap, but one is not a superset of another.
If you want a content script (read: interact with the browser itself), it must be an extension. If you want USB/Serial API, it must be an App.
You must either rethink how to interact with the browser (Apps have some ways to expose themselves to pages) or make both and let them talk to each other.
Related
This is the first time I read about writing Firefox extensions.
What I need is obviously only viable via WebExtensions and both a background and a contentscript. I actually only want to write all open tabs as links in a new tab and then File->Save it. Another alternative Idea was to put it into a JSON Object and save that through a dialog, then I probably could even spare the contentscript but I haven't found anything in the API to download a JSON Object via asking the user to download it via Download Dialog.
Whatever. I think I need to communicate with the content-script then.
I tried to run the following example, but it is not working. When I load the manifest file and open the debugger for extensions, it doesn't log anything and nothing has happened except that the variables myPort and portFromCS seem to be declared without any value.
https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#connection-based_messaging
// manifest.json
{
"manifest_version": 2,
"name": "Save Open Tabs",
"version": "1.0",
"description": "Save my tabs",
"background": {
"scripts": ["background.js"]
},
"content_scripts": [
{
"matches": ["*://*/*"],
"js": ["content.js"]
}
],
"permissions": [
"activeTab",
"tabs"
]
}
// content.js
let myPort=browser.runtime.connect({name:"port-from-cs"});
myPort.postMessage({greeting: "hello from content script"});
myPort.onMessage.addListener((m) => {
console.log("In content script, received message from background script: ");
console.log(m.greeting);
});
// background.js
let portFromCS;
function connected(p) {
portFromCS = p;
portFromCS.postMessage({greeting: "hi there content script!"});
portFromCS.onMessage.addListener((m) => {
portFromCS.postMessage({greeting: "In background script, received message from content script:" + m.greeting});
});
}
browser.runtime.onConnect.addListener(connected);
Why doesn't the example work? Maybe wrong URL matching in the manifest file?
So there is a new API, proposed as a W3C standard, but to use it you need to have this extension for now.
The extension adds an additional document key named monetization, which you can access with document.monetization. And also, the website must have a payment pointer to be able to access it.
I'm trying to access it with an extension I am developing, but I get an undefined error. Here's my manifest.json
{
"manifest_version": 2,
"name": "Test Ext",
"description": "Test Description",
"version": "1.0.0",
"browser_action": {
"default_icon": "icon.png",
"default_pop": "popup.html",
"default_title": "A popup will come here."
},
"permissions": ["activeTab"],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["app.js"]
}
]
}
and in my app.js, I made a simple script to check if document.monetization is loaded.
const tid = setInterval( function () {
if (document.monetization === undefined) return;
console.log('Accessible', document.monetization);
clearInterval( tid );
}, 100 );
But it's not working. How do you manage this?
As we can see in the source code of that extension document.monetization is an expando property on a standard DOM document interface, this property is not a part of DOM, it's essentially a JavaScript object so it's not accessible directly from a content script which runs in an isolated world - all JavaScript objects/variables/expandos are isolated so the page scripts can't see the JS objects of content scripts and vice versa.
In Chrome to access such an expando property you need to run the code in page context and then use standard DOM messaging via CustomEvent to coordinate the code in page context and the content script as shown in a sibling answer in the same topic.
In Firefox you can use wrappedJSObject e.g. document.wrappedJSObject.monetization
I made a working Chrome extension that is not packaged and is just a directory on my computer. I found out that I should be able to port this to Firefox rather easily.
I followed the "Porting a Google Chrome extension" guide on MDN and found that my manifest file is perfect.
I then followed the instructions on how to perform "Temporary Installation in Firefox" of the extension.
However, when I click on any file inside the directory, nothing happens. The extension doesn't load. Any advice? I know the extension works in Chrome fine and loads without error.
manifest.json:
{
"manifest_version": 2,
"name": "ER",
"description": "P",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"background": {
"scripts": [ "background.js" ]
},
"content_scripts": [
{
"matches": [ "SiteIwant" ],
"js": [ "ChromeFormFill.js" ],
"run_at": "document_idle"
}
],
"permissions": [
"*://*/*",
"cookies",
"activeTab",
"tabs",
"https://ajax.googleapis.com/"
],
"externally_connectable": {
"matches": ["SiteIwant"]
}
}
ChromeFormFill.js:
// JavaScript source c
console.log("inside content");
console.log(chrome.runtime.id);
document.getElementById("ID").value = chrome.runtime.id.toString();
Background.js
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
if (request.data === "info") {
console.log("Recieving Info");
return true;
}
});
chrome.tabs.create(
{
url: 'myUrl'
active: true
}, function (tab) {
chrome.tabs.executeScript(tab.id, { file: 'Run.js', runAt: "document_idle" });
});
Run.js will just alert('hi').
It just won't do anything when I try to load it on Firefox; nothing will happen.
Issues:
In manifest.json:
externally_connectable is not supported:1
Firefox does not support externally_connectable. You can follow bug 1319168 for more information. There is, currently, no expected time when this will be implemented.
You will need to communicate between the code on your site and the WebExtension using a different method. The way to do so is to inject a content script and communicate between the site's code and the content script. The common ways to do this are CustomEvent() or window.postMessage(). My preference is CustomEvent().
Using window.postMessage() is like yelling your message outside and hoping that either nobody else is listening, or that they know that they should ignore the message. Other people's code that is also using window.postMessage() must have been written to ignore your messages. You have to write your code to ignore any potential messages from other code. If either of those were not done, then your code or the other code can malfunction.
Using CustomEvent() is like talking directly to someone in a room. Other people could be listening, but they need to know about the room's existence in order to do so, and specifically choose to be listening to your conversation. Custom events are only received by code that is listening for the event type which you have specified, which could be any valid identifier you choose. This makes it much less likely that interference will happen by mistake. You can also choose to use multiple different event types to mean different things, or just use one event type and have a defined format for your messages that allows discriminating between any possible types of messages you need.
matches value needs to be valid (assumed to be intentionally redacted):
You have two lines (one with a trailing ,, one without; both syntactically correct):
"matches": ["SiteIwant"]
"SiteIwant" needs to be a valid match pattern. I'm assuming that this was changed away from something valid to obfuscate the site that you are working with. I used:
"matches": [ "*://*.mozilla.org/*" ]
In Background.js:
The lines:
url: 'myUrl'
active: true
need to be:
url: 'myUrl',
active: true
[Note the , after 'myUrl'.] In addition, myUrl needs to be a valid URL. I used:
url: 'http://www.mozilla.org/',
A Firefox 48 bug (now long fixed):
Your line:
chrome.tabs.executeScript(tab.id, { file: 'Run.js', runAt: "document_idle" });
In Firefox 48 this line is executed prior to the tab being available. This is a bug. It is fixed in Firefox Developer Edition and Nightly. You will need one of those to test/continue development.
Issues in ChromeFormFill.js:
Another Firefox 48 bug (now long fixed):
chrome.runtime.id is undefined. This is fixed in Developer Edition and Nightly.
Potential content script issue:
I'm going to assume your HTML has an element with an ID = 'ID'. If not, your document.getElementById("ID") will be null. You don't check to see if the returned value is valid.
Running your example code
Once all those errors were resolved, and running under Firefox Nightly, or Developer Edition, it worked fine. However, you didn't have anything that relied on being externally_connectable, which won't function.
agaggi noticed that I had forgotten to include this issue in the original version of my answer.
I created an extension that uses native messaging to a host.
The manifest.json of the extension is:
{
"manifest_version": 2,
"version": "1.0",
"name": "Native Messaging Example",
"description": "Send a message to a native application",
"permissions": [
"nativeMessaging"
],
"browser_action": {
"default_popup": "popup.html"
}
}
The popup.html:
<html>
<head>
<script src="./main.js"></script>
</head>
<body>
<button id="buttonToPress">Press</button>
</body>
</html>
The main.js file:
var port = null;
function connect() {
port = chrome.runtime.connectNative('com.google.chrome.example.echo');
port.onMessage.addListener(function(message) {
alert(message);
port.disconnect();
});
port.onDisconnect.addListener(function() {
port = null;
alert(chrome.runtime.lastError.message);
});
var message = {
'filePath': 'C:\\Users\\username\\Desktop\\themes\\Wallpaper\\Architecture\\img13.jpg'
};
port.postMessage(message);
}
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('buttonToPress').addEventListener('click', connect);
});
I have a native application abc.exe.
The native application manifest.json:
{
"name": "com.google.chrome.example.echo",
"description": "Chrome Native Messaging API Example Host",
"path": "./abc.exe",
"type": "stdio",
"allowed_origins": [
"chrome-extensions://fegpbklgdffjmfjmhknpmgepbddbcghk/"
]
}
In the registrey, The Default Value of HKEY_CURRENT_USER\Software\Google\Chrome\NativeMessagingHosts\com.google.chrome.example.echo is C:\Users\username\Desktop\Extension1\NativeApp\manifest.json (This is where the manifest file is physically exists).
The problem is, that each time i run it, it keep saying: 'Specified Native Messaging Host Not Found'... I rechecked my code and it seems to be fine, just like the google's guide of native messaging. The error that logged in the debugger's console is: 'Uncaught Error: Attempting to use a disconnected port object', which i don't know why it keeps happening.
Also, after the chrome.runtime.connectNative, the .exe doesn't start (after seeing in the task manager), and it just seems likes there something that not code-related, but more likely to be in the configuration.
I need some help in figuring it out, so any help would be usefull!
Thanks
notice that chrome extension listed in allowed_origins has to end with /
wrong code (without /):
"allowed_origins": [
"chrome-extension://acajlpgjiolkocfooiankmegidcifefo"
]
correct code:
"allowed_origins": [
"chrome-extension://acajlpgjiolkocfooiankmegidcifefo/"
]
I've managed to work the solution out. I've created the whole pack once again from scratch and set the name of the host application in lowercase. Also i set the key in the registry in 'CURRENT_USER' and it worked well. I guess that maybe the host name should be in lowercase but other than this I don't know where I went wrong. Thanks alot guys for the help!!! I Appreciate it!
I'm not sure relative paths work for Native Host manifests.
In any case, if you compare with the example in the docs, you're using the wrong kind of slash.
I'm trying to write a chrome extension that works with YouTube and need to access some of YouTube's cookie information. I cant seem to get my extension to see any cookies. (Even though I can see them under resources in the "Inspect Element" developer portion of Chrome).
I'm pretty sure I've set up permissions correctly in the manifest 2 file because when I take out the "cookies" permission just to test it I get an error saying "Cannot call method 'getAll'". My current problem is just that no cookies are returned by the callback function.
{
"manifest_version": 2,
"name": "YouTube Viewer",
"description": "This extension is for YouTube videos.",
"version": "1.7",
"icons": {
"128": "ytblack.png"
},
"permissions": [
"cookies",
"https://www.youtube.com/",
"http://www.youtube.com/",
"tabs",
"storage"
],
"background": {
"scripts": ["bootstrap.js"],
"persistent": false
},
"page_action": {
"default_title": "YT View",
"default_icon": "ytblack.png",
"default_popup": "popup.html"
}
}
My manifest calls the bootstrap.js. Inside bootstrap.js there is a call to another file ytview.js but I'm not concerned with that. The code in that is working fine. But inside bootstrap.js my cookies.length is returning as 0 when I look at my "background page" console. The log for "Callback for cookies came in fine." fires correctly. But then it says "cookies.length=0". Like I said, I know the cookies exist because I can see them in the resources.
chrome.tabs.onUpdated.addListener(function(id, info, tab){
// decide if we're ready to inject content script
if (tab.status !== "complete"){
console.log("not yet");
return;
}
if (tab.url.toLowerCase().indexOf("youtube.com/watch") === -1){
console.log("you are not on a YouTube video");
return;
}
chrome.cookies.getAll({domain: "www.youtube.com"}, function(cookies) {
console.log('Callback for cookies came in fine.');
console.log('cookies.length=' + cookies.length);
for(var i=0; i<cookies.length;i++) {
console.log('cookie=' + cookies[i].name);
}
});
chrome.tabs.executeScript(null, {"file": "ytview.js"});
});
Any ideas why no cookies are being returned? Maybe something with "domain" in the .getAll statement? I've tried lots of combinations like www.youtube.com, youtube.com, https://www.youtube.com with no luck.
for future users:
youtube.com use ".youtube.com" as cookie domain to allow the site to share cookies across all youtube subdomains so in your example you should use domain name without 'www' subdomain for example:
chrome.cookies.getAll({domain: "youtube.com"}, function(cookies) {
//...
});
you can clearly see cookies domain using default chrome developer tools
I figured it out. In my manifest I was asking for permission on www.youtube.com but the cookies I was trying to read were on simply youtube.com without the www. Adding the plain youtube.com to the permissions in manifest fixed it.