0

I'm working on a chrome extension that grabs data from a page, then sends a json to my server (opening a new tab and posting data to it) to display a summary.

The problem, is that chrome.scripting.executeScript won't execute on my newly opened tab.

I can read in the console of the newly opened tab this error:

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.

But I don't have any inline code. I found there was a bug and workarounds here, they don't seem to apply for me

Here's the code

    /*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);
            }
        }
    }
}

Worth noting is that I'm under manifest 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"
    ]
  }
}
Zied Hamdi
  • 2,400
  • 1
  • 25
  • 40
  • 1) Your code doesn't click anything so that bug is not related. 2) The code is missing `func:` before postJson in executeScript. 3) The error is usually caused by something in your html e.g. onclick attribute or a ` – wOxxOm Apr 07 '23 at 13:48
  • Thank you for your comment. you're right func: was missing, but it's just when I copy pasted the code, that I made the error sorry. I'm not sure to understand your point 3, but the page loaded contains a very simple Html, this is what the GET query returns: res.send("

    Please wait...

    "); And the error occurs in this newly opened page. (Though I see it in the popup console too)
    – Zied Hamdi Apr 07 '23 at 14:35
  • Looking to the elements of the newly opened tab, I find a , I'm not sure where it is coming from – Zied Hamdi Apr 07 '23 at 14:40
  • 1
    In that case it's probably caused by another extension. – wOxxOm Apr 07 '23 at 15:09
  • You were right, the error was from another extension. Actually chrome.tabs.create was never calling the callback method since I was running it from popup.js, I had to move it to a service worker to get it to work as expected. I'm still wondering how I can call chrome.tabs.create without it throwing an exception: just silently not calling back – Zied Hamdi Apr 08 '23 at 15:16
  • Actually it's written in the docs: The Tabs API can be used by the service worker and extension pages, but not content scripts. – Zied Hamdi Apr 08 '23 at 15:18

0 Answers0