我使用Android(非root)手机进行Web开发,并寻找显示浏览器(Chrome或Firefox)控制台消息的方法。 Android Chrome和Firefox都没有Web检查器/控制台,我也没有找到Firefox(工作)插件。
更新:我无法将手机连接到计算机(ADB,Chrome远程工具......不可用)。
有人能暗示我一个可行的解决方案吗?
我没有找到解决问题的“正常工作”解决方案,所以我做了一个简短的工具,将日志和错误从浏览器发送到后端服务器。
它在Proxy对象周围使用window.console,并实现window.onerror函数将消息发布到服务器。
我构造了代码,将其用作可重用性的expressjs中间件。它并不完美,可能与所有浏览器不兼容,但如果浏览器中没有开发工具,它确实很有用。
任何人都可以通过repl.it测试它。
// Use this module as middleware with expressjs compatible server:
//
// In the server:
// consoleWrapperMiddleware(basePath, app)
// basePath: URL path to send browser messages
// app: expressjs application reference
// return: nothing
//
// In the html page:
// <script src="basePath" />
// basePath: URL path to send browser messages
function consoleWrapper(oldConsole, oldOnerror, serverUrl) {
function _post(log) {
const req = new XMLHttpRequest()
req.open('POST', serverUrl, true)
req.setRequestHeader('Content-Type', 'application/json')
req.send(JSON.stringify(log))
}
const console = new Proxy(oldConsole, {
get: (target, propKey, receiver) => {
const origMethod = target[propKey]
return function (...args) {
if (origMethod === undefined) {
const message = 'unknown console method: '+propKey
_post({ level: 'wrap', message: [message]})
return message
}
else {
let result = origMethod.apply(this, args)
_post({ level: origMethod.name, message: args })
return result
}
}
}
})
const onerror = function(msg, url, line, col) {
if (typeof oldOnerror === 'function')
oldOnerror(arguments)
const content = [ msg, url+':'+line+':'+col ]
_post({ level: 'js-err', message: content })
}
return [ console, onerror ]
}
function consoleWrapperMiddleware(basePath, app) {
app.get(basePath, (req, res) => {
res.status(200).send('[ window.console, window.onerror ] = '+consoleWrapper.toString()+'(window.console, window.onerror, location.protocol.concat("//").concat(location.host).concat("'+basePath+'"))')
console.log('Console wrapper sent')
})
app.post(basePath, (req, res) => {
let body = []
req.on('data', (chunk) => {
body.push(chunk)
}).on('end', () => {
body = Buffer.concat(body).toString()
const logMsg = JSON.parse(body)
console.log('['+logMsg.level+']', ...logMsg.message)
res.writeHead(200)
res.end()
})
})
console.log('Log server listening from',basePath)
}
module.exports = consoleWrapperMiddleware