I'm playing around with web development and looking to test some dynamically generated content, specifically just listing in a Chrome Extension popup all of the links on a site page. I referenced a great resource here but I was testing with an output
tag versus a ul
and the creation of li
for that list to show on the page.
popup.html
<div>
<h3>Page output</h3>
<output id="outputkey3">pages go here</output>
</div>
popup.js
function (tabs) {
var tab = tabs[0];
var url = tab.url;
if (url != null) {
var host = new URL(url).hostname;
...
var outputKey3 = document.getElementById("outputKey3")
if (outputKey3 != null) {
for(var i = document.links.length; i --> 0;) {
if(document.links[i].hostname === host) {
//urls.push(document.links[i].href);
outputKey3.appendChild(document.links[i]);
}
}
}
Even for a single link this does not seem to be working. Not sure if this is meant to be done with a list versus another element that does not format the data with a preceding number or •. What I'd really like to do is just show a list that looks like a new line of data for each index value, perhaps as a bunch of p
's.
You have a couple of things going against you here in your code.
host
is never defined. You probably mean location.host
document.links
includes all links, including the ones you add. Yet another reason to copy the array before changing page contents. appendChild()
will attempt to move the <a>
and this could break the rest of the page. You probably want to clone the element. <output>
may have semantics that are inhibiting the additions. It is intended for computed results and may only have phrasing content . Consider changing to a <div>
if you don't want a <ul>
. Suggestion using clone
var outputKey3 = document.getElementById("outputKey3")
if (outputKey3 != null) {
// Get new array of filtered links
// Document.links is not an array, but can be used by Array.prototype
let links = Array.prototype.filter.call(document.links, function(link) {
return (link.hostname === location.hostname)
&& (link.parentElement !== outputKey3);
});
// For each link, change its value to a clone of it
let newLinks = link.map(function(link) {
return link.cloneNode();
});
// For each clone, add it to the list.
newLinks.forEach(function(link) {
outputKey3.appendChild(link);
});
}
If you must use a for loop:
var outputKey3 = document.getElementById("outputKey3")
if (outputKey3 != null) {
for(var i = document.links.length; i-- > 0;) {
if((document.links[i].hostname === location.hostname)
&& (link.parentElement !== outputKey3)) {
//urls.push(document.links[i].href);
outputKey3.appendChild(document.links[i].cloneNode());
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.