问题
I'm trying to create a tool that monitors the usage of some JavaScript APIs in web pages. My plan is to override the JavaScript API's, store the call information into a global variable, and then send it to content script via postMessage. However, injecting code something like below into the web page causes an "Aw Snap" error.
chrome.devtools.panels.create("Test Dev Panel",
"icon.png",
"panel.html",
function (panel) {
var code = [
"window.counter = 0;",
"Array.prototype.push = function () {",
"window.counter++;",
"}",
"window.addEventListener('message', function(event) {",
"window.postMessage('Array.push() has been called ' + window.counter + ' times.', '*');",
"}, false);"
];
chrome.devtools.inspectedWindow.reload({
injectedScript: code.join('')
});
...
});
It might be a security restriction. But is there any way to achieve my goal?
--- Update --- The error doesn't occur if I remove the postMessage() call. Also, it doesn't if I remove the Array.prototype overriding code. It seems to me that calling the postMessage() and overwriting Array's prototype at the same time are causing the error.
回答1:
It's a syntax error after the Array.prototype.push.
You need to end the line with a semicolon.
...
var code = [
"window.counter = 0;",
"Array.prototype.push = function () {",
"window.counter++;",
"};", //<-- Here
"window.addEventListener('message', function(event) {",
"window.postMessage('Array.push() has been called ' + window.counter + ' times.', '*');",
"}, false);"
];
...
回答2:
The problem is with
"window.counter = 0;",
"Array.prototype.push = function () {",
"window.counter++;",
"}",
"window.addEventListener('message', function(event) {",
"window.postMessage('Array.push() has been called ' + window.counter + ' times.', '*');",
"}, false);"
code, i am not sure what you want to achieve!!
I hope you are aware of the fact Counter is always zero in a frame unless closes the window!
来源:https://stackoverflow.com/questions/15196480/calling-chrome-devtools-inspectedwindow-reload-with-injection-causes-aw-snap