How to use signalr in chrome extensions - google-chrome-extension

I'm trying to use signalr in my chrome extensions but I keep getting
'Uncaught TypeError: Cannot read property 'client' of undefined'
Now I know I need to use a script
<script src="http://localhost:3600/signalr/hubs"></script>
like this, but i can't figure out where and how to use it in chrome extensions.
My manifest file looks like this
"manifest_version": 2,
"name": "Jquery Tests",
"description": "This extension tests jquery.",
"version": "1.0",
"background": {
"scripts": ["jquery-1.9.1.min.js", "jquery.signalR-2.2.1.min.js", "background.js"],
"persistent": true
},
"content_scripts":
[
{
"matches": ["http://*/*", "https://*/*"],
"js": ["jquery-1.9.1.min.js", "jquery.signalR-2.2.1.min.js", "popup.js"]
}
],
"permissions": [
"notifications",
"background",
"tabs", "http://*/*"
],
"browser_action": {
"default_icon": "img/icon.png",
"default_popup": "popup.html"
}
and here is my popup.js where I get the error
$(document).ready(function () {
debugger;
console.log('jquery working in content!');
$.connection.hub.url = "http://localhost:3360/signalr";
$.connection.logging = true;
var ticker = $.connection.notificationHub;
//var ticker = $.connection.tempratureMonitorHub;
//signalr method for push server message to client
ticker.client.notify = function (message) {
console.log("Notification added!");
if (message && message.toLowerCase() == "added") {
updateNotificationCount();
}
}
});
[][1]

In chrome extensions , the dynamically created proxy i.e hubs file is unavailable as files are loaded once per installation.
This file contains information of client and server. To include this information in your extension you need to follow the following steps as mentioned in this link
Install the Microsoft.AspNet.SignalR.Utils NuGet package.
Open a command prompt and browse to the tools folder that contains
the SignalR.exe file. The tools folder is at the following location:
[your solution
folder]\packages\Microsoft.AspNet.SignalR.Utils.2.1.0\tools
Enter the following command:
signalr ghp /path:[path to the .dll that contains your Hub class]
The path to your .dll is typically the bin folder in your project
folder.
This command creates a file named server.js in the same folder as
signalr.exe.
Put the server.js file in an appropriate folder in your project,
rename it as appropriate for your application, and add a reference
to it in place of the "signalr/hubs" reference.

Related

Axios is not defined in background.js (manifest v3)

I am currently working on a chrome Extension.
My desired workflow : content-script.js sends a message to background.js. Once the message is received by background using eventListener, background starts executing a process which includes an axios.post request as well as localStorage.setItem. Since I have migrated the project's manifest to V3, background.js becomes a service worker. Hence while executing the extension, the background.js console says that "axios is not defined" as well as "localStorage is not defined".
Hence I need a way to use this in background.js (manifest v3).
Note : I also tried using chrome.storage.local, but the set function's callback is getting called, but the get function doesn't get any value.
Do not forget to place the "storage" permission in the manifest file.
manifest.json (v3)
{
"name": "Test extenstion",
"description": "Test Extension!",
"version": "1.0",
"manifest_version": 3,
"background": {
"service_worker": "background.js"
},
"action": {},
"permissions": ["storage", "activeTab", "scripting"]
}
Background.js
chrome.storage.sync.set({key: value}, function() {
console.log('Value is set to ' + value);
});
chrome.storage.sync.get(['key'], function(result) {
console.log('Value currently is ' + result.key);
});
Source:
https://developer.chrome.com/docs/extensions/reference/storage/#usage

To print console.log message in active window console instead of background..

I started building chrome extensions. Initially I started with a simple extension which prints the hello in background console. How can I print that in the active window console.
This is my manifest.json file
{
"manifest_version": 2,
"name": "example",
"version": "0.1",
"description": "My Chrome Extension",
"icons": {
},
"background": {
"scripts": ["js/background.js"]
},
"browser_action": {
"default_title": "My test Environment"
},
"permissions": [
"background",
"storage",
"tabs",
"http://*/*",
"https://*/*"
]
}
This is the content of my background.js file
a simple
console.log("hello");
Take a look at Content Script, you could use manifest.json injection or Programming injection to ensure your code run in the context of current webpage.
The former requires Message Passing or Storage to ensure communications between content script with background page;
while as for the latter, Try the following code in background.js
chrome.tabs.executeScript({code: "console.log('hello');"});

content_script not running on GitHub when following links

I am writing a Chrome Extension mainly for Pull Requests on Github Enterprise and have ran into an issue. When the page is loaded via a refresh or direct entering of the url from your browser it runs, when it is ran from clicking a link within Github it does not.
For instance if you go to this page with Pull Requests and click into one of them it will not run. But if you refresh that same page it will run.
manifest.json
{
"name": "Github Sample",
"manifest_version": 2,
"version": "0.0.1",
"description": "Sample",
"permissions": [
"tabs", "<all_urls>",
"http://github.com/*"
],
"content_scripts": [
{
"matches": [ "https://github.com/*" ],
"js": ["github.sample.js"],
"run_at": "document_end"
}
]
}
github.sample.json
// ==UserScript==
// #author Jacob Schoen
// ==/UserScript==
alert("Extension has Ran");
To make this easier I have pushed this to github.
Any ideas on how to address this?
GitHub site uses jquery-pjax library (see How to make github style page transitions by pjax).
Basically you only need to run the content script once and attach pjax event handlers inside an injected <script> element code which will be reusing a jQueryor $ variable of the site.
In those handlers you can send a message with document.dispatchEvent to your content script that will receive it in its window.addEventListener("blabla", ...)
or you can allow the access to chrome.runtime.sendMessage on the github site in manifest.json so that page-injected code will be able to send a message that can be received by the extension in chrome.runtime.onMessageExternal listener.
Alternatively you can use chrome.webNavigation.onHistoryStateUpdated in the background script but that will cause a warning during the installation that the extension can "Read your browsing history" which is a global permission unlike the content script solution.
The working example I came up with, in case it helps anyone else.
manifest.json
{
"name": "Github Sample",
"manifest_version": 2,
"version": "0.0.1",
"description": "Sample",
"permissions": [
"activeTab",
"tabs", "<all_urls>",
"http://github.com/*"
],
"content_scripts": [
{
"matches": [ "https://github.com/*" ],
"js": ["github.sample.js"],
"run_at": "document_idle"
}
],
"web_accessible_resources": ["inject.js"]
}
github.sample.js
// ==UserScript==
// #author Jacob Schoen
// ==/UserScript==
function myAlert() {
alert("Extension has Ran");
}
window.addEventListener("pageLoadTransition", myAlert);
var s = document.createElement('script');
// TODO: add "script.js" to web_accessible_resources in manifest.json
s.src = chrome.extension.getURL('inject.js');
s.onload = function() {
this.parentNode.removeChild(this);
};
(document.head||document.documentElement).appendChild(s);
//still have to load this one for direct page loads
myAlert();
inject.js
$(document).on('pjax:success', function() {
var evt=document.createEvent("CustomEvent");
evt.initCustomEvent("pageLoadTransition", true, true, null);
document.dispatchEvent(evt);
})
I also updated the Github repository with the working example.

Chrome plugin not initializing properly

I am trying to write a chrome plugin,which I defined with the following manifest:
{
"name": "test",
"version": "1.0",
"background": { "scripts": ["background.js"] },
"permissions": [
"tabs", "http://*/*"
],
"browser_action": {
"name": "test",
"icons": ["icon.png"]
},
"manifest_version": 2
}
my background.js file looks like this:
chrome.app.runtime.onLaunched.addListener(function() {
console.log('details', chrome.app.getDetails());
});
When it loads, I see this error on the console:
Uncaught TypeError: Cannot read property 'onLaunched' of undefined
I can't figure out why I am not seeing a properly initialized chrome.app.runtime.
How do I debug this?
Gene
UPDATE:
When I run the following code:
console.log("before connection");
chrome.extension.onConnect.addListener(function(port) {
console.log("connected");
});
I see the first log output (before connection) but not the second; does this mean that it fails to connect to the browser?
chrome.app is undefined because you aren't defining your extension as an app.
Chrome extension can be only one of these in the manifest file:
browser_action, page_action, theme, or app.
In your manifest you're defining an browser action.
So take a deep breath and read the documentation for the manifest file.

On page load event in Chrome extensions

I want to check some values in the content of chrome browser page when it completely loaded
like that
if(document.body.innerText.indexOf("Cat") !=-1)
Where and when can I make my check? please give me an clear example
I read some thing about "Background.html" and "Content script" but I can't do
Register a content script in the manifest file at "run_at": "document_idle" (which is the default) and put your code in the content script file. Then the script will be run when the page is ready.
If you want to detect from the background page whether a page is completely loaded, use the chrome.webNavigation.onCompleted event and do whatever you want, such as calling chrome.tabs.executeScript to execute a content script. This method could be useful over the previous method if the list of URLs is dynamic or if the URL patterns cannot be described using the match pattern syntax.
chrome.webNavigation.onCompleted.addListener(function(details) {
chrome.tabs.executeScript(details.tabId, {
code: ' if (document.body.innerText.indexOf("Cat") !=-1) {' +
' alert("Cat not found!");' +
' }'
});
}, {
url: [{
// Runs on example.com, example.net, but also example.foo.com
hostContains: '.example.'
}],
});
The webNavigation and host permissions have to be set in manifest.json, e.g.:
{
"name": "Test",
"version": "1.0",
"background": { "scripts": ["background.js"] },
"permissions": [ "webNavigation", "*://*/*" ],
"manifest_version": 2
}

Resources