英文:
How to access variables in the script tag outside the script
问题
我需要访问脚本标签内的变量值,并将其放入 meta 标签的内容中。
这是我用于获取图像变量的 JavaScript 代码:
<script>
var pic = document.getElementsByClassName("abc")[0];
var src = pic.getAttribute('src');
console.log(src);
</script>
我需要访问 src
属性的值,然后将其放入 og-image
的 meta 标签内容中:
<meta property="og:image" content="https://example.com/example/**这里应该是src的值**" />
是否可能?如果不行,我还能做什么?
英文:
I need to access the value of the variable inside the script tag to a meta tag content.
This is the JS Code that i used to get the image variable
<script>
var pic = document.getElementsByClassName("abc")[0];
var src = pic.getAttribute('src');
console.log(src);
</script>
I need to access the src tag to the content of the meta og-image
<meta property="og:image" content="https://example.com/example/**src value should be here**" />
Is it possible? or else what can I do?
答案1
得分: 0
UPDATE: 动态创建或修改的Open Graph标签可能不会被任何正在读取它们的工具所读取。
如果你知道服务器上想要的图片,你也可以在那里设置它
$image = "https://example.com/example/image1.jpg";
?>
...
<meta property="og:image" content="<?= $image ?>" />
...
<img class="abc" src="<?= $image ?>"/>
在不太可能的情况下,如果你可以让Google在读取页面时执行JS,那么你可能需要使用createElement,因为如果在加载后执行,meta标签将会被读取,而图片为空。
所以这必须在图片标签之后内联执行
const src = document.querySelector(".abc").src;
const meta = document.createElement("meta");
meta.setAttribute('property','og:image');
meta.setAttribute('content',`https://example.com/example/${src}`);
document.querySelector("head").appendChild(meta);
使用document.write的另一种替代方法
const src = document.querySelector(".abc").src;
document.write(`<meta property="og:image" content="https://example.com/example/${src}" />`);
英文:
UPDATE: Dynamically created or modified Open Graph tags are likely not read by any of the tools that are reading them.
If you know what image you want on the server, you can set it there too
<?PHP
$image = "https://example.com/example/image1.jpg";
?>
...
<meta property="og:image" content="<?= $image ?>" />
...
<img class="abc" src="<?= $image ?>"/>
In the unlikely case you can get Google to execute the JS while reading the page, you likely need to use createElement since the meta tag will be read and the image empty if you do it after load.
So this has to be inline AFTER the image tag
const src = document.querySelector(".abc").src;
const meta = document.createElement("meta");
meta.setAttribute('property','og:image'); meta.setAttribute('content',`https://example.com/example/${src}`);
document.querySelector("head").appendChild(meta)
Alternative with document.write
const src = document.querySelector(".abc").src;
document.write(`<meta property="og:image" content="https://example.com/example/${src}" />`);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论