我正在尝试编写一个生成模拟键盘事件的chrome扩展程序。
This question explains how to generate the keyboard event,但是当我在内容脚本上运行它时会产生以下错误:
error: Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:".
我该怎么做才能解决这个问题?
这是我的manifest.xml
{
"name": "2048 forever",
"description": "SOLVES EVERYTHING",
"version": "2.0",
"permissions": [
"activeTab"
],
"web_accessible_resources": ["keyboard.js"],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {
"default_title": "Solve the things"
},
"manifest_version": 2
}
background.js包含:
chrome.browserAction.onClicked.addListener(function(tab) {
console.log('Turning ' + tab.url + ' red!');
chrome.tabs.executeScript({
code: 'document.body.style.backgroundColor="red"'
});
triggerKeyEvent(document.body, 38);
});
function triggerKeyEvent(element, charCode) {
// We cannot pass object references, so generate an unique selector
var attribute = 'robw_' + Date.now();
element.setAttribute(attribute, '');
var selector = element.tagName + '[' + attribute + ']';
var s = document.createElement('script');
s.textContent = '(' + function(charCode, attribute, selector) {
// Get reference to element...
var element = document.querySelector(selector);
element.removeAttribute(attribute);
// Create KeyboardEvent instance
var event = document.createEvent('KeyboardEvents');
event.initKeyboardEvent(
/* type */ 'keydown',
/* bubbles */ true,
/* cancelable */ false,
/* view */ window,
/* keyIdentifier*/ '',
/* keyLocation */ 0,
/* ctrlKey */ false,
/* altKey */ false,
/* shiftKey */ false,
/* metaKey */ false,
/* altGraphKey */ false
);
// Define custom values
// This part requires the script to be run in the page's context
var getterCode = {get: function() {return charCode}};
var getterChar = {get: function() {return String.fromCharCode(charCode)}};
Object.defineProperties(event, {
charCode: getterCode,
which: getterChar,
keyCode: getterCode, // Not fully correct
key: getterChar, // Not fully correct
char: getterChar
});
element.dispatchEvent(event);
} + ')(' + charCode + ', "' + attribute + '", "' + selector + '")';
console.log('text content: ' + s.textContent);
(document.head||doc.documentElement).appendChild(s);
s.parentNode.removeChild(s);
}