Javascript bookmarklet to take info from one page and submit it to form on another page

扶醉桌前 提交于 2019-12-31 03:14:06

问题


Now that I discovered here that I can't write JavaScript within one page to enter form data on another external page, I'd like to do this with a browser-based bookmarklet instead.

I'm able to access the data on my original page with this bookmarklet code snippet:

javascript:var%20thecode=document.myForm.myTextArea.value;

If I open the external Web-based form manually in the browser, this code changes what's in the text box:

javascript:void(document.externalForm.externalTextArea.value="HELLO WORLD"));

And this bookmarklet code will open a new browser window with the external form:

javascript:newWindow=window.open("http://www.url.com","newWindow");if(window.focus){void(newWindow.focus());}

However, when I try to put these snippets together in a single bookmarklet to open the external form in a new window and change the data inside, I can't access any of the elements in newWindow. For example, this doesn't work to check the existing value of the text area in the new window

javascript:var%20newWindow=window.open("http://www.url.com","newWindow");if(window.focus){void(newWindow.focus());}window.alert(newWindow.document.externalForm.externalTextArea.value);

Once I use the bookmarklet code to open the new window as newWindow, I don't seem to be able to access the elements within that new window. Any suggestions what I'm missing? Thanks.


回答1:


That's because the bookmarklet runs within the sandbox (the environment) of the current web page. Since you're not allowed to access (the DOM of) another page which doesn't have the same protocol, domain name and port, you're not able to access the document property of newWindow when protocols, domains and ports don't match. BTW, the same is true for accessing iframes on a page.

As you're talking about an “external form”, I guess you don't stay on the same domain. The other examples retrieve or manipulate data on the current page (at that moment) and won't error out.

Also see Same origin policy.

Update: About the Delicious (et al.) bookmarklet: its code actually reads:

(function () {
    f = 'http://delicious.com/save?url=' + encodeURIComponent(window.location.href) + '&title=' + encodeURIComponent(document.title) + '&v=5&';
    a = function () {
        if (!window.open(f + 'noui=1&jump=doclose', 'deliciousuiv5', 'location=yes,links=no,scrollbars=no,toolbar=no,width=550,height=550'))
            location.href = f + 'jump=yes'
    };
    if (/Firefox/.test(navigator.userAgent)) {
        setTimeout(a, 0)
    } else {
        a()
    }
})()

So, yes, the parameters are only transferred using a GET request.



来源:https://stackoverflow.com/questions/3348227/javascript-bookmarklet-to-take-info-from-one-page-and-submit-it-to-form-on-anoth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!