The target window of the form (target)
The target
attribute of a form determines where the server response data is displayed after form submission. Proper use of target
can control page navigation logic, avoid unnecessary page refreshes, or enable content updates within specific frames.
Basic Usage of the target
Attribute
The target
attribute is typically used in the <form>
tag to specify the window where the response data will be displayed after submission. It has four standard values:
<form action="/submit" target="_blank">
<!-- Form content -->
</form>
_blank
: Opens in a new window/tab_self
: Opens in the current window (default)_parent
: Opens in the parent frameset_top
: Opens in the full window (exits frames)
Special Applications in Framed Environments
In framed pages, target
can precisely control where form submissions are displayed:
<frameset cols="30%,70%">
<frame name="nav" src="nav.html">
<frame name="main" src="main.html">
</frameset>
<!-- In nav.html -->
<form action="search.php" target="main">
<input type="text" name="query">
<button>Search</button>
</form>
This example shows how to display form submission results in the right main
frame while keeping the left navigation unchanged.
Modern Alternatives in Frontend Development
Although framesets are becoming obsolete, the target
attribute still has special uses in modern single-page applications (SPAs):
<form action="/api/submit" target="hiddenFrame">
<input type="email" name="email">
<button>Subscribe</button>
</form>
<iframe name="hiddenFrame" style="display:none"></iframe>
This pattern enables form submission without refreshing the page. The server response is displayed in a hidden iframe, and JavaScript can be used to process the result:
window.addEventListener('message', (event) => {
if (event.source === frames['hiddenFrame']) {
console.log('Received iframe response:', event.data);
}
});
Comparison with AJAX
Comparison between traditional target
and modern AJAX submissions:
// AJAX approach
document.querySelector('form').addEventListener('submit', (e) => {
e.preventDefault();
fetch('/api/submit', {
method: 'POST',
body: new FormData(e.target)
}).then(response => {
// Process response
});
});
Advantages comparison:
target
requires no JavaScript and has better compatibility- AJAX offers more flexibility for fine-grained control of requests and responses
target
suits simple scenarios, while AJAX is better for complex interactions
Special Handling for File Uploads
Typical use of target
for file uploads:
<form action="/upload" target="uploadFrame" enctype="multipart/form-data">
<input type="file" name="file">
<button>Upload</button>
</form>
<iframe name="uploadFrame" id="uploadFrame"></iframe>
<script>
document.getElementById('uploadFrame').onload = function() {
try {
const response = this.contentDocument.body.innerText;
console.log('Upload result:', JSON.parse(response));
} catch(e) {}
};
</script>
This approach avoids page refreshes while capturing the server's upload response.
Security Considerations
When using target
, note the following:
- Avoid open redirect vulnerabilities
- When using
_blank
, prevent tabnabbing attacks:
<form action="/external" target="_blank" rel="noopener noreferrer">
<!-- Secure external submission -->
</form>
- Validate iframe content sources:
window.addEventListener('message', (event) => {
if (event.origin !== 'https://trusted.domain') return;
// Process message
});
Browser Compatibility Practices
Different browsers may implement target
with subtle differences:
- Older IE versions may not support dynamic
target
changes - Mobile browsers may handle
_blank
differently - Some security settings restrict cross-frame communication
Testing example:
// Dynamically modify target
document.querySelector('form').target =
window.innerWidth < 768 ? '_self' : '_blank';
Interaction with CSS
target
behavior may be affected by CSS:
iframe[name="hiddenFrame"] {
width: 0;
height: 0;
border: none;
visibility: hidden;
}
Incorrect CSS settings may cause:
- Invisible iframes still occupying layout space
- Some browsers blocking content loading in zero-sized iframes
- Hidden content unexpectedly appearing in print styles
Performance Optimization Considerations
Excessive use of target="_blank"
may lead to:
- Proliferation of browser tabs
- Increased memory usage
- Confusing user navigation
Optimization suggestions:
// Detect duplicate submissions
const form = document.querySelector('form');
let lastSubmit = 0;
form.addEventListener('submit', () => {
const now = Date.now();
if (now - lastSubmit < 1000) {
form.target = '_self';
}
lastSubmit = now;
});
Accessibility Adaptations
Ensure target
usage doesn't compromise accessibility:
- Provide visual cues for new window openings
- Allow users to configure whether to open in new windows
- Screen reader adaptations:
<form aria-describedby="target-description">
<span id="target-description" class="sr-only">
This form will open in a new window
</span>
</form>
<style>
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border-width: 0;
}
</style>
Integration with Emerging Technologies
Using target
in Web Components:
<custom-form target="custom-target">
<!-- Shadow DOM content -->
</custom-form>
<script>
class CustomForm extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({mode: 'open'});
shadow.innerHTML = `
<form>
<slot></slot>
</form>
`;
this.form = shadow.querySelector('form');
}
static get observedAttributes() {
return ['target'];
}
attributeChangedCallback(name, oldValue, newValue) {
if (name === 'target') {
this.form.target = newValue;
}
}
}
customElements.define('custom-form', CustomForm);
</script>
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:表单的提交方式(method)
下一篇:注释的写法与作用