2

编辑:我添加了来自 OMDB 的回复

{Response: "False", Error: "Invalid API key!"}
Error: "Invalid API key!"
Response: "False"

我是 Web 开发的新手,我正在尝试构建一个 chrome 扩展,在 netflix 上显示 imdb 分数。我正在使用 OMDB API 来执行此操作。起初我收到以下错误:

“混合内容:'' 处的页面通过 HTTPS 加载,但请求了不安全的 XMLHttpRequest 端点 ''。此请求已被阻止;内容必须通过 HTTPS 提供。”,

但是我只是将 url 中的“http”更改为“https”,然后它就消失了。但是,现在我收到 401 错误,我认为这意味着我的访问被拒绝。 这是完整错误的图片

这是扩展的代码

清单文件:

{
  "manifest_version": 2,
  "name": "1_ratings_netflix",
  "version": "0.1",
  "description": "Display imdb ratings on netflix",
  "content_scripts": [
  {
    "matches": [
      "https://www.netflix.com/*", "https://www.omdbapi.com/*"
    ],
    "js": ["content.js"]
  }
  ],
  "icons": { "16": "icon16.png", "48":"icon48.png"},
  "permissions": [
    "https://www.netflix.com/*", "https://www.omdbapi.com/*"
  ]
}

内容文件:

    function fetchMovieNameYear() {
    var synopsis = document.querySelectorAll('.jawBone .jawbone-title-link');
    if (synopsis === null) {
        return;
    }

    var logoElement = document.querySelectorAll('.jawBone .jawbone-title-link .title');

    if (logoElement.length === 0)
        return;

    logoElement = logoElement[logoElement.length - 1];

    var title = logoElement.textContent;

    if (title === "")
        title = logoElement.querySelector(".logo").getAttribute("alt");

    var titleElement = document.querySelectorAll('.jawBone .jawbone-title-link .title .text').textContent;

    var yearElement = document.querySelectorAll('.jawBone .jawbone-overview-info .meta .year');
    if (yearElement.length === 0)
        return;
    var year = yearElement[yearElement.length - 1].textContent;

    var divId = getDivId(title, year);
    var divEl = document.getElementById(divId);
    if (divEl && (divEl.offsetWidth || divEl.offsetHeight || divEl.getClientRects().length)) {
        return;
    }

    var existingImdbRating = window.sessionStorage.getItem(title + ":" + year);
    if ((existingImdbRating !== "undefined") && (existingImdbRating !== null)) {
        addIMDBRating(existingImdbRating, title, year);
    } else {
        makeRequestAndAddRating(title, year)
    }
};

function addIMDBRating(imdbMetaData, name, year) {
    var divId = getDivId(name, year);

    var divEl = document.getElementById(divId);
    if (divEl && (divEl.offsetWidth || divEl.offsetHeight || divEl.getClientRects().length)) {
        return;
    }

    var synopsises = document.querySelectorAll('.jawBone .synopsis');
    if (synopsises.length) {
        var synopsis = synopsises[synopsises.length - 1];
        var div = document.createElement('div');

        var imdbRatingPresent = imdbMetaData && (imdbMetaData !== 'undefined') && (imdbMetaData !== "N/A");
        var imdbVoteCount = null;
        var imdbRating = null;
        var imdbId = null;
        if (imdbRatingPresent) {
            var imdbMetaDataArr = imdbMetaData.split(":");
            imdbRating = imdbMetaDataArr[0];
            imdbVoteCount = imdbMetaDataArr[1];
            imdbId = imdbMetaDataArr[2];
        }
        var imdbHtml = 'IMDb rating : ' + (imdbRatingPresent ? imdbRating : "N/A") + (imdbVoteCount ? ", Vote Count : " + imdbVoteCount : "");

        if (imdbId !== null) {
            imdbHtml = "<a target='_blank' href='https://www.imdb.com/title/" + imdbId + "'>" + imdbHtml + "</a>";
        }

        div.innerHTML = imdbHtml;
        div.className = 'imdbRating';
        div.id = divId;
        synopsis.parentNode.insertBefore(div, synopsis);
    }
}

function getDivId(name, year) {
    name = name.replace(/[^a-z0-9\s]/gi, '');
    name = name.replace(/ /g, '');
    return "aaa" + name + "_" + year;
}

function makeRequestAndAddRating(name, year) {

    var url = "https://www.omdbapi.com/?i=tt3896198&apikey=**{API_KEY}**" + encodeURI(name)
        + "&y=" + year + "tomatoes=true";

    var xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.withCredentials = true;
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onload = function () {
        if (xhr.status === 200) {
            var apiResponse = JSON.parse(xhr.responseText);
            var imdbRating = apiResponse["imdbRating"];
            var imdbVoteCount = apiResponse["imdbVotes"];
            var imdbId = apiResponse["imdbID"];
            var imdbMetaData = imdbRating + ":" + imdbVoteCount + ":" + imdbId;
            window.sessionStorage.setItem(name + ":" + year, imdbMetaData);
            window.sessionStorage.setItem("metaScore:" + name + ":" + year, metaScore)
            window.sessionStorage.setItem("rotten:" + name + ":" + year, rottenRating);
            addIMDBRating(imdbMetaData, name, year);
            addRottenRating(rottenRating, name, year);
            addMetaScore(metaScore, name, year);
        }
    };
    xhr.send();
}

if (window.sessionStorage !== "undefined") {
    var target = document.body;
    // create an observer instance
    var observer = new MutationObserver(function (mutations) {
        mutations.forEach(function (mutation) {
            window.setTimeout(fetchMovieNameYear, 5);
        });
    });
    // configuration of the observer:
    var config = {
        attributes: true,
        childList: true,
        characterData: true
    };
    observer.observe(target, config);
}
4

1 回答 1

1

发布 OMDB 的请求和响应对您很有帮助(您可以在开发工具的“网络”选项卡中找到它们)。

触发 CORS(跨域请求)错误的一件事是指定application/x-www-form-urlencoded,multipart/form-data或以外的内容类型text/plain。如果我没记错的话,即使没有指定请求的内容类型,OMDB API 也会返回 JSON 响应,因此您应该尝试删除该行:

xhr.setRequestHeader('Content-Type', 'application/json');

更多关于不触发 CORS 的“简单请求”:https ://javascript.info/fetch-crossorigin#simple-requests

您还需要获取 API 密钥 ( https://www.omdbapi.com/apikey.aspx ) 并 **{API_KEY}**在您的代码中替换为该密钥。您还需要将t密钥添加到查询字符串中,否则标题将附加到您的 API 密钥中。

var url = "https://www.omdbapi.com/?i=tt3896198&apikey=**{API_KEY}**" + "&t="
 + encodeURI(name) + "&y=" + year + "tomatoes=true";
于 2020-05-10T21:13:10.270 回答