I'm creating my first plugin and it's function is to scrape reviews from third party retailers like Walmart and Best Buy to provide additional reviews to Amazon shoppers. I've been able to log the reviews in the console, but I'm getting stuck at the final step where I need to append (content.js) it to the element 'reviews' (popup.html). The error I get in the console is "TypeError: Cannot read property 'append' of null". I suspect that content.js is unable to see popup.html as it is another window, therefore unable to append elements to it. Any help is greatly appreciated!
Also on a side note, I'm not sure if background.js is still relevant as it was created with the getting started tutorial. I'm only able to use the chrome plugin at developer.chrome.com and nowhere else. How would I get this to work on 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
}
package-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);
}
});
}
});
background.js
chrome.runtime.onInstalled.addListener(function() {
chrome.storage.sync.set({color: '#3aa757'}, function() {
console.log('The color is green.');
});
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
chrome.declarativeContent.onPageChanged.addRules([{
conditions: [new chrome.declarativeContent.PageStateMatcher({
pageUrl: {hostEquals: 'developer.chrome.com'},
})
],
actions: [new chrome.declarativeContent.ShowPageAction()]
}]);
});
});