I'm writing a simple Chrome extension, the behavior is needed to detect if device is connect to the Internet. I'm currently trying to connect to ping service for checking network status and it is not efficient. Is there any event to which I can listen from Chrome JavaScript API?
There is no specific event in the Chrome extension APIs intended to be used for this purpose.
In "How to detect online/offline event cross-browser?" it is suggested that you can use window.navigator.onLine and the events (from MDN):
window.addEventListener('offline', function(e) { console.log('offline'); });
window.addEventListener('online', function(e) { console.log('online'); });
However, my testing on Windows 10 x64 using Chrome Version 56.0.2924.87 (64-bit) indicated that none of those are valid. When the network cable was physically disconnected, the events did not fire in either the background script, nor a content script In addition, the value of window.navigator.onLine remained true in both. There was a similar lack of activity when the network cable was plugged back in.
Potential events to which you might listen
However, when the network cable was disconnected a webRequest was fired. Specifically the following events:
webRequest.onBeforeRequest -> arg[0]= Object { frameId: -1, method: "GET", parentFrameId: -1, requestId: "10787", tabId: -1, timeStamp: 1487550094371.293, type: "other", url: "https://www.google.com/searchdomaincheck?format=domain&type=chrome", __proto__: Object }
webRequest.onBeforeSendHeaders-> arg[0]= Object { frameId: -1, method: "GET", parentFrameId: -1, requestHeaders: Array[4], requestId: "10787", tabId: -1, timeStamp: 1487550094371.3901, type: "other", url: "https://www.google.com/searchdomaincheck?format=domain&type=chrome", __proto__: Object }
webRequest.onSendHeaders -> arg[0]= Object { frameId: -1, method: "GET", parentFrameId: -1, requestHeaders: Array[4], requestId: "10787", tabId: -1, timeStamp: 1487550094371.437, type: "other", url: "https://www.google.com/searchdomaincheck?format=domain&type=chrome", __proto__: Object }
webRequest.onErrorOccurred -> arg[0]= Object { error: "net::ERR_NAME_NOT_RESOLVED", frameId: -1, fromCache: false, method: "GET", parentFrameId: -1, requestId: "10787", tabId: -1, timeStamp: 1487550096326.291, type: "other", url: "https://www.google.com/searchdomaincheck?format=domain&type=chrome", __proto__: Object }
When the cable was reconnected, the following sequence of webRequests were fired:
webRequest.onBeforeRequest -> arg[0]= Object { frameId: -1, method: "GET", parentFrameId: -1, requestId: "10938", tabId: -1, timeStamp: 1487550516485.3562, type: "other", url: "https://www.google.com/searchdomaincheck?format=domain&type=chrome", __proto__: Object }
webRequest.onBeforeSendHeaders-> arg[0]= Object { frameId: -1, method: "GET", parentFrameId: -1, requestHeaders: Array[4], requestId: "10938", tabId: -1, timeStamp: 1487550516485.523, type: "other", url: "https://www.google.com/searchdomaincheck?format=domain&type=chrome", __proto__: Object }
webRequest.onSendHeaders -> arg[0]= Object { frameId: -1, method: "GET", parentFrameId: -1, requestHeaders: Array[4], requestId: "10938", tabId: -1, timeStamp: 1487550516485.565, type: "other", url: "https://www.google.com/searchdomaincheck?format=domain&type=chrome", __proto__: Object }
webRequest.onHeadersReceived -> arg[0]= Object { frameId: -1, method: "GET", parentFrameId: -1, requestId: "10938", responseHeaders: Array[12], statusCode: 200, statusLine: "HTTP/1.1 200"tabId: -1, timeStamp: 1487550518279.5378, type: "other", url: "https://www.google.com/searchdomaincheck?format=domain&type=chrome", __proto__: Object }
webRequest.onResponseStarted -> arg[0]= Object { frameId: -1, fromCache: false, ip: "216.58.193.68", method: "GET", parentFrameId: -1, requestId: "10938", responseHeaders: Array[12], statusCode: 200, statusLine: "HTTP/1.1 200", tabId: -1, timeStamp: 1487550518279.653type: "other"url: "https://www.google.com/searchdomaincheck?format=domain&type=chrome", __proto__: Object }
webRequest.onCompleted -> arg[0]= Object { frameId: -1, fromCache: false, ip: "216.58.193.68", method: "GET", parentFrameId: -1, requestId: "10938", responseHeaders: Array[12], statusCode: 200, statusLine: "HTTP/1.1 200", tabId: -1, timeStamp: 1487550518279.754type: "other"url: "https://www.google.com/searchdomaincheck?format=domain&type=chrome", __proto__: Object }
So, it appears that good candidates for events to watch are webRequest.onErrorOccurred for going offline and webRequest.onCompleted for going online, both with the URL: https://www.google.com/searchdomaincheck?format=domain&type=chrome.
This would need further testing. It was only tested on the configuration mentioned above.
On my MacBook navigator.onLine works as expected if I turn wifi on and off.
console.log("Is the browser online? "+ navigator.onLine);
With and without wifi enabled...
Related
I'm trying to access my WordPress site from a NodeJS program. Specifically, I'm trying to create a draft post from within a NodeJS program. I've never done this before, and I can't get it work.
I've tried a few ways of doing this. First I used WPAPI and went through the documentation for that. It seemed to connect and get a response from my site but no post was created.
WPAPI method and response log
I've gotten an application password through the Wordpress control panel and I'm using it in the program. The username is from the same page on my panel.
I had installed the JSON Basic Authentication plugin while working with WPAPI, but I deactivated it when I switched to another method.
(Following the documentation on GitHub for WPAPI, I thought I would need to install the superagent bundle so I could use create() I tried installing superagent, requiring wpapi/superagent, and changing the type to module in the package, but when I tried to run it I got an error message saying the module "wpapi/superagent" could not be found. After that I just went back to the general import.)
import WPAPI from "wpapi"
const wp = new WPAPI({
endpoint: 'https://www.example.com/wp-json',
username: 'username',
password: 'application_password'
})
wp.posts().create({
title: 'test post',
content: 'will this work?'
}).then((res) => {
console.log(res)
})
The log:
[
{
id: 1,
date: '2022-09-11T22:33:39',
date_gmt: '2022-09-11T22:33:39',
guid: { rendered: 'https://example.com/?p=1' },
modified: '2022-09-11T22:33:39',
modified_gmt: '2022-09-11T22:33:39',
slug: 'hello-world',
status: 'publish',
type: 'post',
link: 'https://example.com/2022/09/11/hello-world/',
title: { rendered: 'Hello world!' },
content: {
rendered: '\n' +
'<p>Welcome to WordPress. This is your first post. Edit or delete it, then start writing!</p>\n',
protected: false
},
excerpt: {
rendered: '<p>Welcome to WordPress. This is your first post. Edit or delete it, then start writing!</p>\n',
protected: false
},
author: 1,
featured_media: 0,
comment_status: 'open',
ping_status: 'open',
sticky: false,
template: '',
format: 'standard',
meta: {
bgseo_title: '',
bgseo_description: '',
bgseo_robots_index: '',
bgseo_robots_follow: ''
},
categories: [ 1 ],
tags: [],
aioseo_notices: [],
_links: {
self: [Array],
collection: [Array],
about: [Array],
author: [Array],
replies: [Array],
'version-history': [Array],
'wp:attachment': [Array],
'wp:term': [Array],
curies: [Array]
}
},
_paging: {
total: 1,
totalPages: 1,
links: { 'https://api.w.org/': 'https://example.com/wp-json/' }
}
]
Using Fetch to send the post
Now I'm trying code from a guide I found on Medium, and I'm having pretty much the same problem.
I receive a response that I believe means the connection was successful, but no posts have been created on my site, draft or otherwise.
Here's the code:
import fetch from "node-fetch"
const createdPost = await fetch(`https://www.example.com/wp-json/wp/v2/posts`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Basic ${Buffer.from("username:application_password", "utf-8").toString("base64")}`
},
body: JSON.stringify({
title: 'New post title',
content: 'New content'
})
})
console.log(createdPost)
And this is what is logged:
Response {
size: 0,
[Symbol(Body internals)]: {
body: PassThrough {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 6,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: true,
[Symbol(kCapture)]: false,
[Symbol(kCallback)]: null
},
stream: PassThrough {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 6,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: true,
[Symbol(kCapture)]: false,
[Symbol(kCallback)]: null
},
boundary: null,
disturbed: false,
error: null
},
[Symbol(Response internals)]: {
type: 'default',
url: 'https://example.com/wp-json/wp/v2/posts',
status: 200,
statusText: 'OK',
headers: {
'access-control-allow-headers': 'Authorization, X-WP-Nonce, Content-Disposition, Content-MD5, Content-Type',
'access-control-expose-headers': 'X-WP-Total, X-WP-TotalPages, Link',
allow: 'GET',
'cache-control': 'max-age=172800',
connection: 'Upgrade, close',
'content-type': 'application/json; charset=UTF-8',
date: 'Mon, 03 Oct 2022 14:43:35 GMT',
expires: 'Wed, 05 Oct 2022 14:43:35 GMT',
link: '<https://example.com/wp-json/>; rel="https://api.w.org/"',
server: 'Apache',
'transfer-encoding': 'chunked',
upgrade: 'h2',
vary: 'Accept-Encoding,Cookie,Origin,User-Agent',
'x-content-type-options': 'nosniff',
'x-robots-tag': 'noindex',
'x-wp-total': '1',
'x-wp-totalpages': '1'
},
counter: 1,
highWaterMark: 16384
}
}
Summary
Both methods seem to connect but no post is created on my site. Can anyone help? I'm stuck and would really appreciate it.
I'm uploading multiple files separately using axios.
This is the request(all the following code is inside an async function):
const proms = files.map(file => {
let formData = new FormData();
formData.append("file", file);
return axios.post(`/upload/${userId}`, formData)
});
proms will be an array of promises so I proceed to Promise.all it:
const res = await Promise.all(proms)
If I do console.log(res) it shows a successfull response from server as you can see here:
Array(3) [ {…}, {…}, {…} ]
0: Object { data: {…}, status: 200, statusText: "OK", … }
config: Object { timeout: 0, xsrfCookieName: "XSRF-TOKEN", xsrfHeaderName: "X-XSRF-TOKEN", … }
data: Object { fieldname: "file", originalname: "612_photo.jpg", encoding: "7bit", … }
destination: ************************
encoding: "7bit"
fieldname: "file"
filename: "/1648309550808-586868206.jpeg"
mimetype: "image/jpeg"
originalname: "612_photo.jpg"
path: ************************
size: 43267
<prototype>: Object { … }
headers: Object { "content-length": "395", "content-type": "application/json; charset=utf-8" }
request: XMLHttpRequest { readyState: 4, timeout: 0, withCredentials: false, … }
status: 200
statusText: "OK"
<prototype>: Object { … }
1: Object { data: {…}, status: 200, statusText: "OK", … }
2: Object { data: {…}, status: 200, statusText: "OK", … }
length: 3
<prototype>: Array []
But then when I do console.log(res.data) it is undefined. What is happening here?
your response(res) is An array so you cant access res.data ,try :
res.forEach(item=>{console.log(item.data)})
In my react-native application on the login screen I'm working on providing the user with nice error messaging after entering in the incorrect username / password combination. To interact with the API I'm using the library Axios. However when I get an error in the catch statement, I get this ugly error message saying that I have an "unhandled promise rejection" and I cannot do things such as set the components state or navigate to a new page.
I can't see what I'm doing wrong, it looks exactly like examples I've seen in the docs.
In my form submission function I have:
axios.post('http://192.168.1.11:1337/login', {
email: this.state.username,
password: this.state.password
}).then(function (response) {
// This stuff all seems to work great
console.log("The response we got: ", response);
if (response.status == 200) {
console.log("Status code equals 200");
Actions.homepage();
}
}).catch(function (err) {
// Run into big problems when I get an error
console.log("Got an error logging in, here's the message: ", err);
});
Can anyone see what I'm doing wrong here?
P.S. Here is the error message I'm getting back from the server, which get's logged from that console.log("Got an error logging in, here's the message: ", err);:
"Got an error logging in, here's the message:"
{ [Error: Request failed with status code 401]
config:
{ transformRequest: { '0': [Function: transformRequest] },
transformResponse: { '0': [Function: transformResponse] },
headers:
{ Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json;charset=utf-8' },
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: [Function: validateStatus],
method: 'post',
url: 'http://192.168.1.11:1337/login',
data: '{"email":"zach#homies.io","password":"dddddd"}' },
response:
{ data: { message: 'Invalid password', user: false },
status: 401,
statusText: undefined,
headers:
{ map:
{ connection: [ 'keep-alive' ],
date: [ 'Thu, 31 Aug 2017 23:30:21 GMT' ],
'x-powered-by': [ 'Sails <sailsjs.org>' ],
vary: [ 'X-HTTP-Method-Override' ],
'content-length': [ '52' ],
'access-control-allow-credentials': [ '' ],
'access-control-allow-origin': [ '' ],
etag: [ 'W/"34-Ymi4isRxuJ6jE1EIS+AQag"' ],
'access-control-allow-methods': [ '' ],
'access-control-allow-headers': [ '' ],
'access-control-expose-headers': [ '' ],
'content-type': [ 'application/json; charset=utf-8' ] } },
config:
{ transformRequest: { '0': [Function: transformRequest] },
transformResponse: { '0': [Function: transformResponse] },
headers:
{ Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json;charset=utf-8' },
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: [Function: validateStatus],
method: 'post',
url: 'http://192.168.1.11:1337/login',
data: '{"email":"zach#homies.io","password":"dddddd"}' },
request:
{ url: 'http://192.168.1.11:1337/login',
credentials: 'omit',
headers:
{ map:
{ accept: [ 'application/json, text/plain, */*' ],
'content-type': [ 'application/json;charset=utf-8' ] } },
method: 'POST',
mode: null,
referrer: null,
_bodyInit: '{"email":"zach#homies.io","password":"dddddd"}',
_bodyText: '{"email":"zach#homies.io","password":"dddddd"}',
bodyUsed: true } } }
Here is a screenshot of what it looks like on the Android emulator (emulating a Samsung Galaxy S7):
There is nothing wrong in this snippet.
You send a request.
You get a 401 - unauthorized response.
Catch receives the error and logs it.
The interesting part is why you get that unhandled promise rejection error.
But this is thrown somewhere else. So you need to provide more of the code.
Edit:
Perhaps you just have to return your axios promise to the calling function?
I have same problem and I use Firebase for database
I resolve this problem
put database on realtime instead of cloud Firestore like the picture
I hope this worked for you
I have 2 objects generated by sqlite execution:
var info_update = {
id: 270,
cancelados: 2,
concluidos: 2,
total: 914
}
var participantes = [
{id: "10",
nome: "Antonio",
idade: "4",
ativo: 1,
msg: "Backorder"
},
{id: "11",
nome: "Carlos",
idade: "1",
ativo: 1,
msg: "Flagged"
}
]
For send the object I use this method on service:
var headers = {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
};
return $http({
method: "POST",
url: "remote_url.com/action",
data: {info_update: info_update, participantes: participantes},
headers : headers
})
What's the problem?
The parameter info_update it's sent to server, but the parameter participantes it's send empty, as appears in the attached image
I need send ALL data for serve.
How i do it?
Your participantes is not object its array try changing it to object using .map function
I have json string retuned via a ajax call
$.ajax({
type: 'GET',
url: quoteURL,
dataType: 'json',
timeout: 10000,
crossDomain: true,
success: function(result) {
/// required code
}
});
The returned json response from server is
{
_emptyscopedata: [
{},
{}
],
errMsgBuffer: {
errMsg: ''
},
descriptor: [
{
template: 'projects/mobile/market/mostactives.xsl',
componentname: 'getmostactives'
},
{
template: '',
componentname: 'quotelist'
}
],
'invest.mostactive': {
MoverExchange: 'NSDQ',
MoverType: 'ACT',
urlType: ''
},
quotelist: {},
'quote.quote': [
{
timezoneid: 'EST',
change: '0.01',
halted: '0',
type: 'EQ',
bidsize: '2900',
fastmarket: '0',
asksize: '300',
close: '16.64',
timestamp: 'May 18, 2011 3:00 PM EST',
open: '16.64',
productid: 'CSCO:NSDQ:EQ',
bid: '16.63',
exchange: 'NSDQ',
symbol: 'CSCO',
news: '0',
quotetype: '2',
percentchange: '0.0006',
symboldesc: 'CISCO SYS INC COM',
price: '16.65',
utctime: '1305748800',
volume: '92738240',
high: '16.66',
quotestatus: '0',
low: '16.34',
ask: '16.64',
timestring2: '05/18/11 04:00 PM ET'
},
{
timezoneid: 'EST',
change: '0.04',
halted: '0',
type: 'EQ',
bidsize: '91200',
fastmarket: '0',
asksize: '241000',
close: '2.14',
timestamp: 'May 18, 2011 3:00 PM EST',
open: '2.13',
productid: 'SIRI:NSDQ:EQ',
bid: '2.17',
exchange: 'NSDQ',
symbol: 'SIRI',
news: '0',
quotetype: '2',
percentchange: '0.0187',
symboldesc: 'SIRIUS XM RADIO INC COM',
price: '2.18',
utctime: '1305748800',
volume: '74540998',
high: '2.2',
quotestatus: '0',
low: '2.12',
ask: '2.18',
timestring2: '05/18/11 04:00 PM ET'
}
]
}
I want to show some of the values of the response on the site. But I am not able to retrieve the values.
Can someone help.
$.ajax({
type: 'GET',
url: quoteURL,
dataType: 'json',
timeout: 10000,
crossDomain: true,
success: function(result) {
alert(result.descriptor[0].template);
}
});
and if you wanted to loop through all descriptors:
$.each(result.descriptor, function() {
var template = this.template;
var componentname = this.componentname;
// TODO: process the template and componentname
});
or:
alert(result['invest.mostactive'].MoverExchange);
etc... depending on what you want to show
You can use define a global variable in case you want to use the response out the success function scope.
Just use
var cachedResp;//at global scope
$.ajax({
type: 'GET',
url: quoteURL,
dataType: 'json',
timeout: 10000,
crossDomain: true,
success: function(result) {
cachedResp = result; //this is now available out of the function
}
});