Error Encountered with WebKitSubtleCrypto while utilizing dispatchMessage within a Safari Extension

I'm currently working on developing a Safari extension that allows users to share screenshots of webpages. However, I've encountered an issue when trying to pass the image back to Swift - it triggers an error that causes Safari to become unstable and abruptly terminates my task midway through the process.

The concept behind this extension is that when a user clicks on a toolbar button, any selected text and a screenshot of the webpage are saved. I'm attempting to pass both of these pieces of data through the userInfo dictionary. When I run my code with the dispatchMessage call commented out, I don't encounter any errors. But if I uncomment the dispatch call, I receive the following error message:

 WebKitSubtleCrypto is deprecated. Please use SubtleCrypto instead.

Below is my JavaScript code:

document.addEventListener("DOMContentLoaded", function(event) {
    safari.self.addEventListener("message", handleMessage);
});

function handleMessage(event) {
    var selectedText = window.getSelection().toString();
    var screenshot;

    if (window.top === window) {
  html2canvas(document.getElementsByTagName('html')).then(function(canvas) {
        screenshot = convertCanvasToImage(canvas);
        console.log("canvas image: " + screenshot)
        safari.extension.dispatchMessage("test", {"selectedText": selectedText, "screenshot" : canvas});
        });
    }
}

function convertCanvasToImage(canvas) {
   var image = new Image();
   image.src = canvas.toDataURL("image/png");
   return image;
}

The html2canvas library (latest version - 0.5.0-beta4) is included in another file packaged with the extension.

Edit 1

After conducting further tests, it appears that this error is related solely to passing the 'screenshot' object in the messageDispatch call. If I remove the screenshot and only pass the selectedText data, everything functions as expected. Additionally, I've attempted to pass the screenshot as a canvas without running it through the 'convertCanvasToImage()' function, but I continue to encounter the same error.

Answer №1

The problem was actually related to how I initialized the image data before converting the canvas to a data URL.

Instead of:

function convertCanvasToImage(canvas) {
   var image = new Image();
   image.src = canvas.toDataURL("image/png");
   return image;
}

I changed it to:

function convertCanvasToImage(canvas) {
    var imageData = canvas.toDataURL("image/png")
    return imageData;
}

This fixed the issue.

On the Swift side, this is how I decoded that data (please note the use of force unwrapping here):

    let imageString = userInfo?["screenshot"] as! String
    let imageData = NSData.init(contentsOf: NSURL(string: imageString) as! URL)
    let image = NSImage(data: imageData as! Data)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Alternative solution to fix navigation issue in Flex 4.5 when navigatetoURL is not functioning as intended

Perhaps you are aware of the compatibility issues that Google Chrome and Safari have when using navigatetoURL, as it only works in Internet Explorer. To address this problem, I found a code snippet on a forum which consists of a JavaScript function embedde ...

Issue in Three.js: The lower part of the mesh is not rendering

After converting a mesh from .obj to json using the official converter (https://github.com/mrdoob/three.js/tree/master/utils/converters/obj), I noticed that the mesh displays correctly from one side, but not the other. This seems to be due to the fact that ...

Complete the loop of ajax calls array instead of terminating when an error occurs in one of the calls

I am attempting to create a loop of ajax calls from an array and save each data result to be printed once all calls have been successfully received. The issue arises when any ajax call returns an error, causing the entire process to be aborted and the cal ...

What is the best way to retrieve a specific children element from a JSON object in JavaScript based on a keyname and value match

Recently, I encountered a JSON data structure that looked like this: var jsonData = { "id": 0, "content": "abc", "children" : [{ "id": 1, "content": "efg", "children" : [] } { "id": 2, "c ...

Tips for accessing the following element within an array using a for loop with the syntax for (let obj of objects)

Is there a way to access the next element in an array while iterating through it? for (let item of list) { // accessing the item at index + 1 } Although I am aware that I could use a traditional for loop, I would rather stick with this syntax. for (i ...

Developing a interactive quiz platform with JavaScript

I recently attempted to develop a straightforward quiz page using Javascript. Everything seemed to be working fine, until I noticed that when I clicked the submit button in the browser, the text generated in the paragraph section (via Script) vanished almo ...

The addition of one hour to the date time format increases the total time

Currently, I am retrieving a datetime column value from a database table as 2015-03-04 21:00:00 UTC. When attempting to convert this format into a datetime picker, the following code is used: date = moment($("#event_start").val()); // date time value fro ...

Error: The function $(...).jqGrid is not defined for caption: 'Array-Based Student List Loading'

Encountered an error when trying to load the Index view. I am attempting to implement JQGrid using the jQuery grid plugin. I have included several JS files and CSS for JQGrid in the view, but I am unable to create the grid using the plugin. I am using ver ...

Tips for positioning HTML elements at the exact mouse location as it moves, without any delay?

Currently, I am in the process of developing a web-based drawing application that does not rely on using a canvas. My decision to avoid using a canvas is because I plan to incorporate CSS Keyframes into the HTML elements upon placement. This approach allow ...

Navigating to a destination with react-leaflet: step-by-step guide

As a newcomer to React and Leaflet, I am trying to create a feature where users can input coordinates, trigger an event on pressing enter, and then have the map fly to those generated coordinates. I am successfully generating the latitude and longitude coo ...

Received an unexpected GET request while attempting to modify an HTML attribute

After clicking a button in my HTML file, a function is called from a separate file. Here is the code for that function: function getRandomVideoLink(){ //AJAX request to /random-video console.log("ajax request"); var xhttp = new XMLHttpRequest( ...

Instructions for including a script and stylesheet exclusively on a single page of a website

I need to incorporate these two lines onto a single page of my website: <script src="//cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.js"></script> As well as <link href="//cdnjs.cloudflare.com/ajax/libs/OwlCa ...

Value as a String inside an Object

I am encountering an issue with using the obj to store string values in my project. The strings contain commas, and for some reason, it is not working as expected. const resizedUrl ={ 'mobile': "'images','400x/images' ...

Unlock the App Store instead of iTunes Store using react-native-version-check

I am currently using react-native-version-check to trigger the opening of the app store or play store if an update is available. However, on iOS it redirects to the iTunes store instead of the desired AppStore location. Below is the code in question: ...

Finding the maximum value among multiple variables in AngularJS

After performing calculations, I have assigned specific values to variables. console.log("Gain_weight is "+ Gain_weight); console.log("Gain_smoking is "+ Gain_smoking); console.log("Gain_exercising is "+ Gain_exercising); console.log("Gain_foodhabits ...

What is the best way to transfer the API Response Time from one Fetch function to a separate asynchronous function?

After successfully obtaining the API Response Time (duration) using the 'makeAPICall' function, I am now faced with the task of passing this duration variable value to another asynchronous function. Can anyone assist me in finding a solution to a ...

Sending a document to a nodeJS server

Client code: var data = new FormData(); data.append(fileName, blob, 'test.html'); fetch('http://localhost:3000/', { method: 'POST', headers: { }, body: data }).then( response => { console.log(res ...

Attempting to use vue-test-utils-getting-started with the standard configuration results in a "Preset Not Found" error during

Currently, I am in the process of conducting a unit test by referring to the official guide provided. To do so, I have cloned the demonstration repository named vue-test-utils-getting-started. To replicate the issue, follow these steps: After cloning vu ...

What is the best way to show a message of success once the user has been redirected to the homepage?

Currently, I have a registration form utilizing AJAX and PHP for validation. Error messages can be displayed on the registration page if the user does not correctly fill out the form. Upon successful registration, the user is redirected back to the home pa ...

In Vue Js, the function createUserWithEmailAndPassword does not exist within _firebase_config__WEBPACK_IMPORTED_MODULE_3__.default

My createUserWithEmailAndPassword function seems to be malfunctioning. Here is the code snippet I am using - config.js import firebase from 'firebase/app' import 'firebase/firestore' import 'firebase/auth' const firebaseCon ...