我已经被困了几个小时,试图在content.js和popup.js之间实现发送和接收消息。我已经阅读了很多关于它是如何完成的主题但每个都有自己的变化。我在content.js上从第三方网站生成评论,但我似乎无法弄清楚如何正确地做到这一点以及在哪里做。我是一个新手Javascript用户,任何帮助将不胜感激。
我在控制台中遇到的错误是" TypeError:无法读取属性'追加' null "。
另外在旁注中,我只能在 developer.chrome.com 上使用Chrome插件,而不是其他地方。我如何才能在 amazon.com 上使用它?
的manifest.json
{
"name": "Reviews",
"version": "1.0",
"description": "Get additional product reviews",
"permissions": [
"https://www.walmart.com/*",
"http://www.walmart.com/*",
"https://www.amazon.com/*",
"http://www.amazon.com/*",
"activeTab",
"declarativeContent",
"storage"
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"manifest_version": 2
}
包lock.json
{
"requires": true,
"lockfileVersion": 1,
"dependencies": {
"fetch-jsonp": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/fetch-jsonp/-/fetch-jsonp-1.1.3.tgz",
"integrity": "sha1-nrnlhboIqvcAVjU40Xu+u81aPbI="
}
}
}
popup.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button id="reviews-btn">Get Reviews</button>
<script src="popup.js"></script>
<ul id="reviews"></ul>
</body>
</html>
popup.js
'use strict';
let getReview = document.getElementById('reviews-btn');
getReview.onclick = function(element) {
chrome.tabs.executeScript({
file: "content.js"
});
};
content.js
fetch("https://api.walmartlabs.com/v1/search?apiKey=vck5ypdbw4jnhuceesmjjce5&query=NETGEAR&format=json")
.then(function (response) {
return response.json();
}).then(function (responseText) {
if (responseText) {
var product = responseText.items[0];
var itemId = product.itemId;
fetch(`https://api.walmartlabs.com/v1/reviews/${itemId}?apiKey=vck5ypdbw4jnhuceesmjjce5&format=json`)
.then(function (response) {
return response.json();
}).then(function (responseText) {
var reviews = document.getElementById('reviews');
var walmartReviews = responseText.reviews
for (i in walmartReviews) {
var li = document.createElement('li');
li.innerHTML = walmartReviews[i].reviewText;
reviews.append(li);
}
});
}
});