使用Javascript获取元标题和描述



我正在尝试从我添加到URL字段的任何网站获取元标题和描述。我在这里错过了什么?如果我在URL字段中放了一些东西,然后单击"获取",则不会显示任何内容。当我说";https://www.espn.com/"对于JS函数中的URL,它将整个网站拉到预览中。

我错过了什么?

//DISPLAY META
$(document).ready(function() {

$('.seoTitle').on('keyup', function() {
$('.seoTitleNew').text($(this).val());
});

$('.seoMeta').on('keyup', function() {
$('.seoMetaNew').text($(this).val());
});

});
//END DISPLAY META

//GET URL META
function myMetaFunction() {
var url = document.getElementById("seoUrlFetch").innerHTML;
//if you try "https://www.espn.com/" below for url it pulls in the whole page
$.get(url, function(data) {
$(data).filter('meta[property="og:title"]').attr("content");
document.getElementById("seoTitleDisplay").innerHTML = data;
}); 

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<div>
<span>URL </span><input type="text" id="seoUrlFetch" class="seoURL" placeholder="Enter single URL or paste multiple URLs to fetch data from..." autocapitalize="none"> <button id="fetchURLButton" onclick="myMetaFunction()">Fetch</button>
</div>
<div>
<span>Title </span><input class="seoTitle" type="text" placeholder="Your title..." autocapitalize="none">
</div>
<div>
<span>Meta </span><textarea class="seoMeta" type="text" placeholder="Your meta description..." autocapitalize="none"></textarea>
</div>
</div>
<div>
<div>
<p id="seoTitleDisplay" class="seoTitleNew"></p>
</div>

<div>
<span class="seoMetaNew"></span>
</div>
</div>

看起来您正在将innerHTML设置为整个返回的文档。

根据jquery的文档,filter函数不会改变您传递给它的原始参数——它构造了一个经过筛选的新jquery对象(https://api.jquery.com/filter/)。

尝试以下

const filteredData = $(data).filter('meta[property="og:title"]').attr("content");
document.getElementById("seoTitleDisplay").innerHTML = filteredData;

最新更新