简体   繁体   中英

Why does Sharepoint accidentally reloads page when copying to clipbpard?

I have created some HTML/JavaScript site that generates some program code. When program code was created it is shown in a textarea element. The user can klick on a button and the code is copied to the clipboard.

In regular HTML/JavaScript this is working fine. But now I ported it to a Webpart Snippet in SharePoint 2013.

When the user klicks the button, the code is successfully stored as text in the users clipboard. But in the very same moment the SharePoint site reloads and that resets all the settings in the snippet. I cannot understand why the JavaScript code is acting so much different when running in a snippet in SharePoint. This Is the Code:

    ...

    copy2clip = function() {
        document.getElementById('TextCASL').select();
        try {
            var successful = document.execCommand('copy');
            var msg = successful ? 'successful' : 'unsuccessful';
            console.log('Copying text command was ' + msg);
        } catch (err) {
            console.log('Oops, unable to copy');
        }
    }

    ...

</script>
<button onclick=jacascript:copy2clip();>Copy to clipboard</button>

Just return false at the end of click handler to prevent the page from submitting:

copy2clip = function() {
    document.getElementById('TextCASL').select();
    try {
        var successful = document.execCommand('copy');
        var msg = successful ? 'successful' : 'unsuccessful';
        console.log('Copying text command was ' + msg);
    } catch (err) {
        console.log('Oops, unable to copy');
    }

    return false;
}

The behavior is not particular to SharePoint, but in your case it might be happening because the button in inside a <form> element. So the click on it is causing the form to be submitted to the server.

Alternatively, setting type="button" on the button's markup should be fine as well:

<button type="button" onclick=jacascript:copy2clip();>Copy to clipboard</button>

Page reloads when I add copy function in custom django admin page.

Even if I write nothing in onclick function, page also reloads.

So the reason is not the function.

When I change button element to input element, it works.

<input type="button" onclick="myCopy('{obj.id}')" value="Copy"/>

When you use "button" tag, it will by default submit the form irrespective of whatever is there in your function. So it will result in refreshing the current browser window. But if you use " input type=button " then it will not submit the form by default, it will check for the function action.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM