Search code examples
javascripthtmldombookmarklet

Javascript Bookmarklet that writes Meta keywords into new (Browser) Tab


So i managed to get this working (script extracts site meta keywords and writes it into DOM)

javascript:(function metaKeywords() { metaCollection = document.getElementsByTagName('meta'); for (i=0;i<metaCollection.length;i++) { nameAttribute = metaCollection[i].name.search(/keywords/);if (nameAttribute!= -1) { document.write(metaCollection[i].content); } } } )();

and now I just need to figure out how to make the script write / open into a new browse tab

nearest script I could find for opening into new tab is this:

function openWindow( url ){window.open(url, '_blank');window.focus();}

but have no idea how to integrate the two. Please help!


Solution

  • Try this:

    (function metaKeywords() {
        metaCollection = document.getElementsByTagName('meta');
        for (i = 0; i < metaCollection.length; i++) {
            nameAttribute = metaCollection[i].name.search(/keywords/);
            if (nameAttribute != -1) {
                var str = (metaCollection[i].content);
                window.open('javascript:document.write("' + str + '")');
                window.focus();
            }
        }   
    })();
    

    Or as a one liner:

    javascript:(function metaKeywords() { metaCollection = document.getElementsByTagName('meta'); for (i = 0; i < metaCollection.length; i++) { nameAttribute = metaCollection[i].name.search(/keywords/); if (nameAttribute != -1) { var str = (metaCollection[i].content); window.open('javascript:document.write("' + str + '")'); window.focus();}}})();
    

    You open up a new window (make sure it isn't blocked) and just set it to write the string into the contents. Jsfiddle won't allow document.write so I can't show you a demo, but it works on my machine(TM).