programing tip

JavaScript를 사용하여 페이지의 메타 태그를 변경할 수 있습니까?

itbloger 2020. 8. 31. 07:33
반응형

JavaScript를 사용하여 페이지의 메타 태그를 변경할 수 있습니까?


헤드에 div를 넣고 display : none을 표시하면 JavaScript를 사용하여 표시하는 것보다 작동합니까?

편집하다:

AJAX에 물건을로드했습니다. 그리고 내 AJAX가 사이트의 "메인"부분을 변경함에 따라 메타 태그도 변경하고 싶습니다.


예, 할 수 있습니다.

몇 가지 흥미로운 사용 사례가 있습니다. 일부 브라우저와 플러그인은 메타 요소를 구문 분석하고 다른 값에 대한 동작을 변경합니다.

Skype : 전화 번호 파서 끄기

<meta name="SKYPE_TOOLBAR" content="SKYPE_TOOLBAR_PARSER_COMPATIBLE">

iPhone : 전화 번호 파서 끄기

<meta name="format-detection" content="telephone=no">

Google 크롬 프레임

<meta http-equiv="X-UA-Compatible" content="chrome=1">

모바일 장치 용 뷰포트 정의

<meta name="viewport" content="width=device-width, initial-scale=1.0">

이것은 JavaScript로 변경할 수 있습니다. 참조 : iPhone 뷰포트 배율 버그 수정

메타 설명

일부 사용자 에이전트 (예 : Opera)는 책갈피에 대한 설명을 사용합니다. 여기에서 개인화 된 콘텐츠를 추가 할 수 있습니다. 예:

<!DOCTYPE html>
<title>Test</title>
<meta name="description" content="this is old">
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.2.js'></script>

<button>Change description</button>

<script type='text/javascript'>
$('button').on('click', function() {
    // Just replacing the value of the 'content' attribute will not work.
    $('meta[name=description]').remove();
    $('head').append( '<meta name="description" content="this is new">' );
});
</script>

그래서 그것은 단지 검색 엔진에 관한 것이 아닙니다.


네, 그렇습니다.

예 : 메타 설명을 설정하려면 :

document.querySelector('meta[name="description"]').setAttribute("content", _desc);

다음과 같은 것을 사용합니다 (jQuery 사용).

$('meta[name=author]').attr('content', 'New Author Name');

그러나 메타 태그는 일반적으로 JavaScript를 실행하지 않고 문서가로드 될 때만 스크랩되기 때문에 대부분 의미가 없습니다.


예를 들어 다음과 같이 jQuery 호출을 사용하여 메타를 변경할 수 있습니다.

$('meta[name=keywords]').attr('content', new_keywords);
$('meta[name=description]').attr('content', new_description);

Google 호출을 통해 ajax 콘텐츠를 인덱싱 할 것이라고 말했기 때문에 지금 중요 하다고 생각 합니다. 그리고 이제 그들은 그것을 검증 수 있습니다 .#!hashes_escaped_fragment_


자바 스크립트를 사용하여 페이지의 메타 태그를 변경할 수 있습니다. 다음은 Javascript 전용 접근 방식입니다.

document.getElementsByTagName('meta')["keywords"].content = "My new page keywords!!";
document.getElementsByTagName('meta')["description"].content = "My new page description!!";
document.title = "My new Document Title!!";

I have verified that Google does index these client side changes for the code above.


meta-tags are part of the dom and can be accessed and -i guess- changed, but search-engines (the main consumers of meta-tags) won't see the change as the javascript won't be executed. so unless you're changing a meta-tag (refresh comes to mind) which has implications in the browser, this might be of little use?


It should be possible like this (or use jQuery like $('meta[name=author]').attr("content");):

<html>
<head>
<title>Meta Data</title>
<meta name="Author" content="Martin Webb">
<meta name="Author" content="A.N. Other">
<meta name="Description" content="A sample html file for extracting meta data">
<meta name="Keywords" content="JavaScript, DOM, W3C">

</head>

<body>
<script language="JavaScript"><!--
if (document.getElementsByName) {
  var metaArray = document.getElementsByName('Author');
  for (var i=0; i<metaArray.length; i++) {
    document.write(metaArray[i].content + '<br>');
  }

  var metaArray = document.getElementsByName('Description');
  for (var i=0; i<metaArray.length; i++) {
    document.write(metaArray[i].content + '<br>');
  }

  var metaArray = document.getElementsByName('Keywords');
  for (var i=0; i<metaArray.length; i++) {
    document.write(metaArray[i].content + '<br>');
  }
}
//--></script>
</body>

</html>

$(document).ready(function() {
  $('meta[property="og:title"]').remove();
  $('meta[property="og:description"]').remove();
  $('meta[property="og:url"]').remove();
  $("head").append('<meta property="og:title" content="blubb1">');
  $("head").append('<meta property="og:description" content="blubb2">');
  $("head").append('<meta property="og:url" content="blubb3">');
});

var metaTag = document.getElementsByTagName('meta');
for (var i=0; i < metaTag.length; i++) {
    if (metaTag[i].getAttribute("http-equiv")=='refresh')
        metaTag[i].content = '666';
    if (metaTag[i].getAttribute("name")=='Keywords')
        metaTag[i].content = 'js, solver';
}

simple add and div atribute to each meta tag example

<meta id="mtlink" name="url" content="">
<meta id="mtdesc" name="description" content="" />
<meta id="mtkwrds" name="keywords" content="" />

now like normal div change for ex. n click

<a href="#" onClick="changeTags(); return false;">Change Meta Tags</a>

function change tags with jQuery

function changeTags(){
   $("#mtlink").attr("content","http://albup.com");
   $("#mtdesc").attr("content","music all the time");
   $("#mtkwrds").attr("content","mp3, download music, ");

}

No, a div is a body element, not a head element

EDIT: Then the only thing SEs are going to get is the base HTML, not the ajax modified one.


Yes, it is possible to add metatags with Javascript. I did in my example

Android not respecting metatag removal?

But, I dont know how to change it other then removing it. Btw, in my example.. when you click the 'ADD' button it adds the tag and the viewport changes respectively but I dont know how to revert it back (remove it, in Android).. I wish there was firebug for Android so I saw what was happening. Firefox does remove the tag. if anybody has any ideas on this please note so in my question.


have this in index

<link rel="opengraph" href="{http://yourPage.com/subdomain.php}"/>

have this in ajaxfiles og:type"og:title"og:description and og: image

and add this also

<link rel="origin" href={http://yourPage.com}/>

then add in js after the ajaxCall

FB.XFBML.parse();

Edit: You can then display the correct title and image to facebook in txt/php douments(mine are just named .php as extensions, but are more txt files). I then have the meta tags in these files, and the link back to index in every document, also a meta link in the index file for every subfile..

if anyone knows a better way of doing this I would appreciate any additions :)


This seems to be working for a little rigidly geometrically set app where it needs to run on both mobile and other browsers with little change, so finding the mobile/non-mobile browser status and for mobiles setting the viewport to device-width is needed. As scripts can be run from the header, the below js in header seems to change the metatag for device-width Before the page loads. One might note that the use of navigator.userAgent is stipulated as experimental. The script must follow the metatag entry to be changed, so one must choose some initial content, and then change on some condition.

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>  
  var userAgentHeader = navigator.userAgent ; 
  var browserIsMobileOrNot = "mobileNOT" ; 
  if( userAgentHeader.includes( "Mobi" ) ) { 
    browserIsMobileOrNot = "mobileYES" ; 
    //document.querySelector('meta[name="viewport"]').setAttribute( "content", "width=device-width, initial-scale=1.0" );
  } else { 
    browserIsMobileOrNot = "mobileNOT" ;  
    document.querySelector('meta[name="viewport"]').setAttribute( "content", "");
  }
</script>

<link rel="stylesheet" href="css/index.css">

. . . . . .


If we don't have the meta tag at all, then we can use the following:

var _desc = 'Out description';
var meta = document.createElement('meta');
meta.setAttribute('name', 'description');
meta.setAttribute('content', _desc);
document.getElementsByTagName('head')[0].appendChild(meta);

You can use more simpler and lighter solution:

document.head.querySelector('meta[name="description"]').content = _desc

참고URL : https://stackoverflow.com/questions/2568760/is-it-possible-to-use-javascript-to-change-the-meta-tags-of-the-page

반응형