Политика безопасности содержимого и connect-src при выполнении запроса AJAX POST в расширениях Chrome? - PullRequest
0 голосов
/ 24 октября 2018

Я использовал расширение Chrome для динамического добавления кнопки на панель навигации на странице профиля Instagram.Когда эта кнопка нажата, она выполняет запрос POST, используя API выборки для REST API.

Однако при нажатии кнопки выборка не выполняется.Я получаю сообщение об ошибке консоли:

Отказался подключиться к 'https://jsonplaceholder.typicode.com/posts', поскольку он нарушает следующую директиву политики безопасности содержимого: "connect-src' self 'https://instagram.com https://www.instagram.com https://.www.instagram.com https://graph.instagram.com https://.graph.instagram.com https://.cdninstagram.com https://api.instagram.com wss: //www.instagram.com wss: //edge-chat.instagram.com https://.facebook.com https://.fbcdn.net https://.facebook.net chrome-extension: // my-unique-chrome-extension-id-here ".

Что мне нужно изменить на content_security_policy в manifest.json, чтобы сделать запись AJAXзапросы успешно?

// manifest.json
{
  "name": "Content Security Experiment",
  "version": "0.0.1",
  "description": "Test content security",
  "manifest_version": 2,
  "content_scripts": [
    {
      "matches": ["https://www.instagram.com/*"],
      "js": ["contentScript.js"],
      "css": ["styles.css"],
      "run_at": "document_end"
    }
  ],
  "content_security_policy": "script-src 'self'; object-src 'self'; connect-src 'self' https://jsonplaceholder.typicode.com/post"
}

// contentScript.js
window.onload = function() {
    console.log("fired");
    addNavBarButton();
};

/**
 * Adds a button to the nav bar of an Instagram profile page. Buggy? Might need a manual reload in browser to get button to appear.
 */
function addNavBarButton() {
    const navBar = document.body.querySelector("div._47KiJ");
    // Create main container div
    const navBarDiv = document.createElement("div");
    navBarDiv.classList.add("Xr0ey");

    // Create the div for the button
    const navBarButton = document.createElement("div");
    navBarButton.classList.add("aButton");
    const buttonText = document.createTextNode("CLICK");
    navBarButton.appendChild(buttonText);
    navBarDiv.appendChild(navBarButton);

    // Add the button to the container div
    navBar.appendChild(navBarDiv);

    // onclick handler
    navBarButton.onclick = buttonClickHandler;
}

function buttonClickHandler() {
    // A Fake Online REST API for Testing and Prototyping - https://github.com/typicode/jsonplaceholder#how-to
    fetch('https://jsonplaceholder.typicode.com/posts', {
        method: 'POST',
        body: JSON.stringify({
            title: 'foo',
            body: 'bar',
            userId: 1
        }),
        headers: {
            "Content-type": "application/json; charset=UTF-8"
        }
    })
        .then(response => response.json())
        .then(json => console.log(json))
        .catch(error => console.log("Something went wrong.", error));
}
.aButton {
    cursor: pointer;
    height: 24px;
    width: 24px;
    margin-left: 30px;
    background-size: contain;
}
...