How to open a fixed URL + what's in the clipboard via a script & bind it to a shortcut?

Solution 1:

The following example AppleScript code will do as you asked:

set the clipboard to "questions/392514/i-want-to-write-a-script-to-open-a-fixed-url-whats-in-the-clipboard-ex-open"

set myURL to "https://apple.stackexchange.com/" & (the clipboard)

tell application "Safari" to ¬
    tell its first window to ¬
        set its current tab to ¬
            (make new tab with properties {URL:myURL})

If you run the example AppleScript code, as is, it will open to your question.

The first line of code is just there for testing purposes as well as the "https://apple.stackexchange.com/" part of myURL. Change it to what you want and comment out or delete the first line to use it normally.

To incorporate that into something more robust to account for the current state of Safari, the following example AppleScript code handles the typical different scenarios:

set the clipboard to "questions/392514/i-want-to-write-a-script-to-open-a-fixed-url-whats-in-the-clipboard-ex-open"

set myURL to "https://apple.stackexchange.com/" & (the clipboard)

tell application "Safari"
    activate
    if (count documents) is equal to 0 then
        make new document
        repeat until exists its first window
            delay 0.01
        end repeat
        set URL of its current tab of its first window to myURL
    else
        set firstTabURL to URL of its first tab of its first window
        if {"favorites://", "topsites://", missing value} contains firstTabURL then
            set URL of its current tab of its first window to myURL
        else
            tell its first window to ¬
                set its current tab to ¬
                    (make new tab with properties {URL:myURL})
        end if
    end if
end tell 

Again, the first line of code is just there for testing purposes as well as the "https://apple.stackexchange.com/" part of myURL. Change it to what you want and comment out or delete the first line to use it normally.

Note: The example AppleScript code was tested on macOS High Sierra.


Note: The example AppleScript code is just that and does not contain any error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. Additionally, the use of the delay command may be necessary between events where appropriate, e.g. delay 0.5, with the value of the delay set appropriately.