Отказался выполнять встроенный скрипт, поскольку он нарушает CSP.
Я работаю над расширением Chrome, которое собирает данные со страницы, а затем отправляет json на мой сервер (открывая новую вкладку и отправляя на нее данные) для отображения сводки.
Проблема в том, чтоchrome.scripting.executeScript
не будет выполняться на моей недавно открытой вкладке.
Я могу прочитать в консоли недавно открытой вкладки эту ошибку:
Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' 'wasm-unsafe-eval' 'inline-speculation-rules'". Either the 'unsafe-inline' keyword, a hash ('sha256-l0EBls9+5sHTJ5FqNSzs3FP1dCE2sL/MgTgPGh29hSg='), or a nonce ('nonce-...') is required to enable inline execution.
Но у меня нет встроенного кода . Я обнаружил, что здесь была ошибка и обходные пути , похоже, они мне не подходят.
Вот код
/*global chrome*/
const CV_URL = 'http://localhost:3001/cv'
document.addEventListener('DOMContentLoaded', () => {
const generateBtn = document.getElementById('generateBtn');
generateBtn.addEventListener('click', () => {
chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
chrome.tabs.sendMessage(tabs[0].id, {action: 'scrapeUserResume'}, (response) => {
if (response) {
const data = response.data;
console.log("sending data to create resume: ", data)
openTabAndPostData(data)
}
});
});
});
});
async function openTabAndPostData(jsonData) {
chrome.tabs.create({url: CV_URL}, async function (tab) {
// Pass URL and JSON data as parameters to content script
await chrome.scripting.executeScript({
target: {tabId: tab.id},
func: postJson,
args: [tab.url, jsonData]
});
// Handle response
if (chrome.runtime.lastError) {
// Request failed
console.error('Failed to execute content script:', chrome.runtime.lastError);
} else {
// Request successful
console.log('Content script executed successfully');
}
});
}
function postJson(url, jsonData) {
// Create XHR object
const xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
// Convert JSON data to string and send in the request
xhr.send(JSON.stringify(jsonData));
// Handle response
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
// Request successful
console.log('XHR POST request successful:', xhr.responseText);
} else {
// Request failed
console.error('XHR POST request failed:', xhr.statusText);
}
}
}
}
Стоит отметить, что я использую манифест v3.
{
"name": "LinkedIn CV Generator",
"version": "1.0",
"manifest_version": 3,
"description": "Extracts information from LinkedIn profiles to generate a JSON object for a CV page.",
"permissions": [
"identity",
"activeTab",
"tabs",
"scripting"
],
"host_permissions": [
"<all_urls>"
],
"content_scripts": [
{
"matches": [
"https://www.linkedin.com/in/*"
],
"js": [
"content.js",
"background.js",
"static/js/main.[HASH].js"
]
}
],
"background": {
"service_worker":"background.js"
},
"action": {
"default_popup": "popup.html",
"default_title": "LinkedIn CV Generator",
"default_icon": {
"16": "icons/logo16.png",
"32": "icons/logo32.png",
"48": "icons/logo48.png",
"128": "icons/logo128.png"
}
},
"oauth2": {
"client_id": "xxxx",
"scopes": [
"https://www.googleapis.com/auth/drive"
]
}
}