■102050 / inTopicNo.10) |
Re[8]: 別タブで開くaタグのリンクについて |
□投稿者/ WebSurfer (2709回)-(2023/06/12(Mon) 15:51:01)
|
■No102045 (くま さん) に返信
> またはこちら
> windowObjectReference = window.open('', windowName);
> let elem = windowObjectReference.document.createElement('a');
> elem.href = url;
> elem.rel = "noreferrer";
> windowObjectReference.document.body.appendChild(elem);
> elem.click();
>
なるほど、それで複数 a タグをクリックしても同じ window で表示されて要求ヘッダに Refer
は含まれなくなりますね。
それを MDN の記事、
Window.open()
https://developer.mozilla.org/ja/docs/Web/API/Window/open
の「既存のウィンドウを再利用して target="_blank" を防止する」のセクションにある
サンプルコードに組み込んで、同じ a タグを続けてクリックしても要求が出ないように
するのが良さそうです。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript">
let windowObjectReference = null; // global variable
let previousURL; /* global variable that will store the
url currently in the secondary window */
function openRequestedSingleTab(url) {
if (windowObjectReference === null || windowObjectReference.closed) {
let a = document.createElement("a");
a.href = url;
a.rel = "noreferrer";
windowObjectReference = window.open('', 'SingleSecondaryWindowName');
windowObjectReference.document.body.appendChild(a);
a.click();
} else if (previousURL !== url) {
let a = document.createElement("a");
a.href = url;
a.rel = "noreferrer";
windowObjectReference = window.open('', 'SingleSecondaryWindowName');
windowObjectReference.document.body.appendChild(a);
a.click();
/* if the resource to load is different,
then we load it in the already opened secondary window and then
we bring such window back on top/in front of its parent window. */
windowObjectReference.focus();
} else {
windowObjectReference.focus();
}
previousURL = url;
/* explanation: we store the current url in order to compare url
in the event of another call of this function. */
}
window.addEventListener('DOMContentLoaded', () => {
const links = document.querySelectorAll("a[target='SingleSecondaryWindowName']");
for (const link of links) {
link.addEventListener(
"click",
(event) => {
openRequestedSingleTab(link.href);
event.preventDefault();
},
false
);
}
});
</script>
</head>
<body>
<a href="default" target="SingleSecondaryWindowName" rel="noreferrer">Default</a>
<br />
<a href="about" target="SingleSecondaryWindowName" rel="noreferrer">About</a>
<br />
<a href="contact" target="SingleSecondaryWindowName" rel="noreferrer">Contact</a>
</body>
</html>
|
|