admin管理员组文章数量:1236534
There is a Google Chrome extension with content script
that handles JS errors occured on all tabs pages. But the problem is that no one of usual methods of getting errors stack trace does not work.
For example, there is a code in content script
of Chrome extension:
window.addEventListener('error', function(event) {
console.log(event.error.stack); // event.error will be null
}, false);
If I call this code inside web page, so event.error
will contains Error
object with stack
property.
Same problem with trying to get stack trace using:
console.log((new Error()).stack));
Does anybody knows some working issue to get error stack trace inside content script
of Chrome extension?
Error stack trace must be received as string
or Array
, means not just like some output in JS console by calling console.trace()
.
How to reproduce:
- Download !ENw00YAC!92gBZEoLCO9jPsWyKht4dbjYyo0Zk-PU5YAj0h88-3Q
- Unpack
jzen.zip
to some/jsen
folder - Open
chrome://extensions
in your Google Chrome, enableDeveloper mode
.png - Click
Load unpacked extension
button and select path to/jsen
folder - Open
/jsen/content.js
file and addconsole.log('JSEN', e.error.stack);
insidewindow.addEventListener('error', function(e) {
- Go to .htm and see result in JS console(Ctrl+Shift+J)
- Try to edit
/jsen/content.js
to get correct error trace - To reinitialize Chrome extension source code click .png
There is a Google Chrome extension with content script
that handles JS errors occured on all tabs pages. But the problem is that no one of usual methods of getting errors stack trace does not work.
For example, there is a code in content script
of Chrome extension:
window.addEventListener('error', function(event) {
console.log(event.error.stack); // event.error will be null
}, false);
If I call this code inside web page, so event.error
will contains Error
object with stack
property.
Same problem with trying to get stack trace using:
console.log((new Error()).stack));
Does anybody knows some working issue to get error stack trace inside content script
of Chrome extension?
Error stack trace must be received as string
or Array
, means not just like some output in JS console by calling console.trace()
.
How to reproduce:
- Download https://mega.co.nz/#!ENw00YAC!92gBZEoLCO9jPsWyKht4dbjYyo0Zk-PU5YAj0h88-3Q
- Unpack
jzen.zip
to some/jsen
folder - Open
chrome://extensions
in your Google Chrome, enableDeveloper mode
https://i.sstatic.net/OLwpa.png - Click
Load unpacked extension
button and select path to/jsen
folder - Open
/jsen/content.js
file and addconsole.log('JSEN', e.error.stack);
insidewindow.addEventListener('error', function(e) {
- Go to http://xpart.ru/_share/js.htm and see result in JS console(Ctrl+Shift+J)
- Try to edit
/jsen/content.js
to get correct error trace - To reinitialize Chrome extension source code click https://i.sstatic.net/2LIEa.png
- 1 You should mention that you want the stack trace as a string, it is not enough to have it displayed in the console. The question is a bit misleading. – Tibos Commented Dec 2, 2013 at 8:27
2 Answers
Reset to default 13 +500As you mention, the error
property of the event object is null
when capturing the event in Content Script context, but it has the required info when captured in webpage context. So the solution is to capture the event in webpage context and use messaging to deliver it to the Content Script.
// This code will be injected to run in webpage context
function codeToInject() {
window.addEventListener('error', function(e) {
var error = {
stack: e.error.stack
// Add here any other properties you need, like e.filename, etc...
};
document.dispatchEvent(new CustomEvent('ReportError', {detail:error}));
});
}
document.addEventListener('ReportError', function(e) {
console.log('CONTENT SCRIPT', e.detail.stack);
});
//Inject code
var script = document.createElement('script');
script.textContent = '(' + codeToInject + '())';
(document.head||document.documentElement).appendChild(script);
script.parentNode.removeChild(script);
The techniques used are described in:
- https://stackoverflow.com/a/9517879/1507998
- https://stackoverflow.com/a/9636008/1507998
The problem
The main problem is JS context isolation, i.e. the fact that "Content scripts execute in a special environment called an isolated world". This is a good thing, of course, because it avoids conflicts and enhances security, but yet a problem if you want to catch errors.
Each isolated world sees its own version of the (window) object. Assigning to the object affects your independent copy of the object...
...neither one can read the other's event handler. The event handlers are called in the order in which they were assigned.
A solution
On posiible solution (a.k.a. hack) consists of the following steps:
- Inject some code into the web-page itself (and try to make is as non-obtrusive as possible to avoid conflicts).
- In that code register an event listener for errors and store the error data in a DOM-node's dataset.
- Finally, from within the content script, use a MutationObserver to watch for changes in this DOM-node's attributes.
- Once a change in the specified data-<...> attribute is detected, grab its new value and there you have your error info right in your content script :)
The source code
Below is the source code of a sample extension that does exactly that.
manifest.json:
{
"manifest_version": 2,
"name": "Test Extension",
"version": "0.0",
"content_scripts": [{
"matches": ["*://*/*"],
"js": ["content.js"],
"run_at": "document_start",
"all_frames": true
}],
}
content.js:
/* This <script> element will function as an "error-proxy"
* for the content-script */
var errorProxy = document.createElement('script');
errorProxy.id = 'myErrorProxyScriptID';
errorProxy.dataset.lastError = '';
/* Make the content as non-obtrusive as possible */
errorProxy.textContent = [
'',
'(function() {',
' var script = document.querySelector("script#' + errorProxy.id + '");',
' window.addEventListener("error", function(evt) {',
' script.dataset.lastError = evt.error.stack;',
' }, true);',
'})();',
''].join('\n');
/* Add the <script> element to the DOM */
document.documentElement.appendChild(errorProxy);
/* Create an observer for `errorProxy`'s attributes
* (the `data-last-error` attribute is of interest) */
var errorObserver = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if ((mutation.type === 'attributes')
&& (mutation.attributeName === 'data-last-error')) {
console.log('Content script detected new error:\n',
errorProxy.dataset.lastError);
}
});
});
errorObserver.observe(errorProxy, { attributes: true });
本文标签: javascriptHow to get errors stack trace in Chrome extension content scriptStack Overflow
版权声明:本文标题:javascript - How to get errors stack trace in Chrome extension content script? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1739509367a2166416.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论